How do I loop through options in the select box
I want to loop through options in the select box that has attribute set as "data-status = YES" and select this options and apply all this options in red color .How can i do that .This "data-status" is written through php
<select id ="test1">
<option value = "1" data-status='YES'>one</option>
<option value = "2" data-status='NO'>2</option>
<option value = "3" data-status='YES'>3</option>
<option value = "4" data-status='YES'>4</option>
</select>
$(document).ready(function(){
$('#tes开发者_如何学编程t1 > option:selected').each(function() {
// alert($(this).text() + ' ' + $(this).val());
if($(this).data-status==YES"){
$(this).css()
}
});
});
How do i apply the font-weight :bold attribute to the option that has the data-status =YES i added it using .addClass("bold")
I believe this is what you are looking for
$('#test1 option').each(function() {
// alert($(this).text() + ' ' + $(this).val());
if($(this).data('status') == 'YES'){
$(this).css('color','red');
}
});
demo http://jsfiddle.net/gaby/6N88x/
If you want to also select multiple options then you will need to add the multiple
attribute to the select
tag.
<select id ="test1" multiple>
and change the script to
$('#test1 option').each(function() {
// alert($(this).text() + ' ' + $(this).val());
if($(this).data('status') == 'YES'){
$(this)
.css('color','red')
.attr('selected',true);
}
});
demo http://jsfiddle.net/gaby/6N88x/1/
No need to loop, this should do it.
$("#test1 > option[data-status=YES]").css("color","red");
Try this:
if($(this).data('status') == 'YES')
I don't think you can set the color of an <option>
, but you can loop through the <select>
like so:
$(document).ready(function(){
$('#test1 > option').each(function() {
if($(this).data('status')=="YES") {
$(this).html('test'); // or whatever
}
});
});
Change $(this).data-status
to $(this).attr('data-status')
.
$('#test1 > option').filter(function() {
return $(this).data("status") == "YES";
}).remove(); // or whatever
Demo: http://jsfiddle.net/xxzLA/
http://api.jquery.com/filter
精彩评论