Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple descendants with jQuery?

I have this form:

<form name="customize">
    Only show results within 
        <select name="distance" id="slct_distance">
            <option>25</option>
            <option>50</option>
            <option>100</option>
            <option value="10000" selected="selected">Any</option>
    </select> miles of zip code
    <input type="text" class="text" name="zip_code" id="txt_zip_code" />
    <span id="customize_validation_msg"></span>
</form>

How can I select the input and select with one jQuery selector?

I tried this but it selected all of the selects and inputs on the page:

$("form[name='customize'] select,input")
like image 279
Greg Avatar asked Nov 09 '08 18:11

Greg


People also ask

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

What is jQuery descendant?

With jQuery you can traverse down the DOM tree to find descendants of an element. A descendant is a child, grandchild, great-grandchild, and so on.

What is descendant selector in Javascript?

Definition and Usage. The ("parent descendant") selector selects all elements that are descendants of a specified element. A descendant of an element could be a child, grandchild, great-grandchild, etc, of that element.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

The comma in the selector string separates completely separate expressions, just like in CSS, so the selector you've given gets the select elements within the form named "customize" and all inputs on the form (as you've described). It sounds like you want something like this:

$("form[name='customize'] select, form[name='customize'] input")

or if you're not into repitition, this:

$("form[name='customize']").children("select, input")
like image 138
Kevin Gorski Avatar answered Oct 19 '22 07:10

Kevin Gorski


A shorter syntax $(selector,parentselector) is also possible. Example on this page :

// all spans
$("span").css("background-color","#ff0");

// spans below a post-text class
$("span", ".post-text").css("background-color","#f00");

Edit -- I forgot the particular case of several kind of children !

// spans and p's below a post-text class
$("span,p", ".post-text").css("background-color","#f00");
like image 31
vincent Avatar answered Oct 19 '22 07:10

vincent