i want to loop through all dropdown selects with a certain class name and add an item to it and i am just struggling with the correct selector
EDIT: I must be doing something wrong as most of the upvoted accepted answer dont seem to work so i think there must be some quirk in my code. I have pasted both the HTML and the jquery code below. let me know if this makes sense.
HTML:
<select onfocus="this.enteredText='';" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress = "return selectItem();" class="componentSelect" id="components0" name="applicationUpdater.dependencies[0].componentName" >
<option value= 5 >Client</option>
<option value= 79 >Server</option>
</select>
<select onfocus="this.enteredText='';" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress = "return selectItem();" class="componentSelect" id="components1" name="applicationUpdater.dependencies[0].componentName" >
<option value= 5 >Client</option>
<option value= 79 >Server</option>
</select>
etc . . .
jquery code:
$('select.componentSelect').each(function() {
var select = $(this);
$(select).children('option').each(function() {
if ($(this).text() == currentComponentName) {
$(this).remove();
}
});
});
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.
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.
The :button selector selects button elements, and input elements with type=button.
Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").
You should use the .class selector.
// select every <select> element with classname "yourclassname"
$('select.yourclassname').each(function() {
// $(this) now refers to one specific <select> element
// we append an option to it, like you asked for
$(this).append(
$('<option value="foo">Bar</option>');
);
});
For more information about how to properly select elements with jQuery, take a look at http://docs.jquery.com/Selectors.
To answer your new question, you can use the following line to remove all <option>
s containing a currentComponentName
:
$('select.componentSelect option:contains("' + currentComponentName + '")').remove();
Demo
Give this a shot:
$('select.className').each(function() {
var currentSelect = $(this);
// ... do your thing ;-)
});
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