Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
Awan Avatar asked Dec 08 '10 12:12

Awan


People also ask

How do you select an element with a particular class selected?

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.

Does jQuery use CSS selectors to select elements?

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: $() .


2 Answers

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 #names, you can use the attribute selector on the id:

$("input[id=name]").val('Hello World!'); 
like image 196
Kobi Avatar answered Oct 25 '22 17:10

Kobi


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

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

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

like image 28
Marcos Alexandre Sedrez Avatar answered Oct 25 '22 17:10

Marcos Alexandre Sedrez