[jquery] jQuery form input select by id

Code

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

Question

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

I only ask because I might have other inputs called 'b' somewhere else in my page and I want to make sure I'm getting the value from the correct form.

This question is related to jquery

The answer is


You can do that using the descendant selectors:

 $("#a #b")

However, id values are supposed to be unique on a page.


For example like this:

var value = $("#a").find("#b").val()

Why not just:

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

Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev() function either.


If you have more than one element with the same ID, then you have invalid HTML.

But you can acheive the same result using classes instead. That's what they're designed for.

<input class='b' ... >

You can give it an ID as well if you need to, but it should be unique.

Once you've got the class in there, you can reference it with a dot instead of the hash, like so:

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

or

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

which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).


You can just target the id directly:

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

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

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