<form id='a'>
<input id='b' value='dave'>
</form>
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.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.
To achieve the best performance when using :odd to select elements, first select the elements using a pure CSS selector, then use . filter(":odd") . Selected elements are in the order of their appearance in the document.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
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();
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