How to select a specific form element in jQuery?

I have two forms:

<form id='form1' name='form1'> <input name='name' id='name'> <input name='name2' id='name2'> </form> <form id='form2' name='form2'> <input name='name' id='name'> <input name='name2' id='name2'> </form> 

Now I want to insert text in the form2 name field. I am using the following jQuery code , but it populates the form1 name field .

 $("#name").val('Hello World!'); 

So, how to select only certain form elements?

+64
jquery jquery-selectors
Dec 08 '10 at 12:17
source share
5 answers

It is not true to have the same identifier twice, so #name only finds the first one.

You can try:

 $("#form2 input").val('Hello World!'); 

Or

 $("#form2 input[name=name]").val('Hello World!'); 

If you are stuck with an invalid page and want to select all #name s, you can use the attribute selector on id:

 $("input[id=name]").val('Hello World!'); 
+122
Dec 08 '10 at 12:21
source share

although this is not valid html, but you can use the selector context to limit your selector in your case it will look like this:

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

+8
Dec 08 2018-10-12
source share

I prefer the descendant selector id of your # form2, for example:

 $("#form2 #name").val("Hello World!"); 

http://api.jquery.com/descendant-selector/

+6
Aug 07 '15 at 19:12
source share

I know that the question is how to configure the input, but just in case, if you want to install a combo box, then (I’m looking for a network for it and haven’t found anything, and this place seems to be the right place to guide others)

If you have a form with a set of ID attributes (for example, frm1) and you want to set a specific special command with a list, without a set of identifiers, but a name attribute attribute (for example, district); then use

 $("#frm1 select[name='district'] option[value='NWFP']").attr('selected', true); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <form id="frm1"> <select name="district"> <option value="" disabled="" selected="" hidden="">Area ...</option> <option value="NWFP">NWFP</option> <option value="FATA">FATA</option> </select> </form> 
+2
Oct 02 '17 at 8:07 on
source share
 $("#name", '#form2').val("Hello World") 
-2
Nov 28 '13 at 6:28
source share



All Articles