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?
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.
jQuery uses CSS-style selectors to select parts, or elements, of an HTML page. It then lets you do something with the elements using jQuery methods, or functions. To use one of these selectors, type a dollar sign and parentheses after it: $() .
It isn't valid to have the same ID twice, that's why #name
only finds the first one.
You can try:
$("#form2 input").val('Hello World!');
Or,
$("#form2 input[name=name]").val('Hello World!');
If you're stuck with an invalid page and want to select all #name
s, you can use the attribute selector on the id:
$("input[id=name]").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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With