[jquery] How to select specific form element in jQuery?

I have two form like this:

<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 name field of form2. I am using following jQuery code but it fill name field of form1.

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

So how to select specific form elements only?

This question is related to jquery jquery-selectors

The answer is


I know the question is about setting a input but just in case if you want to set a combobox then (I search net for it and didn't find anything and this place seems a right place to guide others)

If you had a form with ID attribute set (e.g. frm1) and you wanted to set a specific specific combobox, with no ID set but name attribute set (e.g. district); then use

_x000D_
_x000D_
$("#frm1 select[name='district'] option[value='NWFP']").attr('selected', true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <form id="frm1">_x000D_
        <select name="district">_x000D_
            <option value="" disabled="" selected="" hidden="">Area ...</option>_x000D_
            <option value="NWFP">NWFP</option>_x000D_
            <option value="FATA">FATA</option>_x000D_
        </select>_x000D_
    </form>
_x000D_
_x000D_
_x000D_


$("#name", '#form2').val("Hello World")

I prefer an id descendant selector of your #form2, like this:

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

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


although it is invalid html but you can use selector context to limit your selector in your case it would be like :

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

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