开发者

What is the correct jquery selector to get all select dropdowns with a certain class name?

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();
            }
        });

    });


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 ;-)
});


You need to use the .className selector, like this:

$('select.className')

This selector combines the element selector (matching all <select> elements) with the className selector (matching all elements that contain the className class) to find all <select> elements with that class.


Your posted jQuery code works for me, as long as I define currentComponentName to be one of the options of your select. Aron Rotteveel's answer is very close, but the append part is a bit off, try this:

$('select.componentSelect').each(function() { 
    $(this).append('<option value="foo">Bar</option>'); 
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜