Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector to get form by name

I have the following HTML:

<form name="frmSave">...</form> 

Just to know, I am not able to modify the HTML in order to add an id or something else.

This is what I tried to get the form element by it's name:

var frm = $('form[name="frmSave"]');  console.log(frm); 

(but I believe the above code will try to get a children element with the frmSave name inside the form which is not what I need).

How can I achieve this, is it possible to get the form by just the name and using a selector?


Update:

I was doing the wrong way in my original code (I was using a space aka "combinator" in the selector) and not in the code snippet from here so jQuery was trying to get any children element with the name needed and I was asking myself what was wrong since nothing was returned.

The accepted answer gives a better explanation about this so a little space could change everything - I will sleep properly next time :-)

like image 429
Oscar Jara Avatar asked Dec 06 '12 16:12

Oscar Jara


People also ask

How can I select an element by name with jQuery?

How to select an element by name with jQuery? The JavaScript getElementsByName() method can be used to select the required element and this can be passed to a jQuery function to use it further as a jQuery object.

How to select form using jQuery?

$( "form :selected" ); In order to get the best performance using :selected , first select elements with a standard jQuery selector, then use . filter( ":selected" ) , or precede the pseudo-selector with a tag name or some other selector.

How to access form elements in jQuery?

The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data.

How do you find the value of an element with a name instead of ID?

Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element. Save this answer.


1 Answers

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

like image 50
Christian Avatar answered Oct 16 '22 04:10

Christian