Select jQuery input form by id

the code

<form id='a'> <input id='b' value='dave'> </form> 

Question

How can I get the value from the input "b", at the same time make sure that it is inside the "a" (something like $('#a:input[id=b]') ).

I just ask because I can have other inputs called "b" somewhere else on my page, and I want to make sure that I get the value from the correct form.

+8
jquery
source share
5 answers

You can do this with descendant selectors:

  $("#a #b") 

However, the id values ​​must be unique on the page.

+24
source share

For example, for example:

 var value = $("#a").find("#b").val() 
+10
source share

You can directly target the id:

 var value = $('#b').val(); 

If you have more than one element with this identifier on the same page, it will not work properly. You must ensure that the identifier is unique.

If you really use the code for different pages and only want to find the element on those pages where id: s are embedded, you can simply use the child operator, i.e. space:

 var value = $('#a #b').val(); 
+2
source share

If you have multiple elements with the same identifier, you have invalid HTML.

But you can get the same result using classes. This is what they are for.

 <input class='b' ... > 

You can also specify its identifier if you need, but it must be unique.

Once you have a class, you can reference it with a dot instead of a hash, for example:

 var value = $('#a .b').val(); 

or

 var value = $('#a input.b').val(); 

which will limit it to the elements of class "b", which are inputs in the form (which is similar to what you are asking).

+2
source share

Why not just:

 $('#b').click(function () { var val = $(this).val(); }) 

Or, if you don’t click it (and I think you won’t), and you will use the submit button, you can use the prev() function.

0
source share

All Articles