Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery form input select by id

Tags:

jquery

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.

like image 502
Robert Johnstone Avatar asked Apr 19 '11 12:04

Robert Johnstone


People also ask

How do you select element by id in jQuery?

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.

How do I know which ID is clicked in jQuery?

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.

How will you select only the odd anchor tags on the page?

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.

How do you target a class in jQuery?

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.


1 Answers

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();
like image 96
Guffa Avatar answered Sep 18 '22 04:09

Guffa