Select multiple descendants with jQuery?
-
07-07-2019 - |
Question
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")
Solution
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")
OTHER TIPS
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");
For me your suggestion worked. You could also use
form[name='customize'] select, form[name='customize'] input
Both selectors work as I see it. Maybe the the problem lies somewhere else?
I tried
$("form[name='customize'] select, input").css( 'font-size', '80px' );
on your example HTML. The font size for select and input changed.
--- edit ---
My suggestion above is the right one. It selects just the elements in the customize-form.