开发者

Replacing empty select boxes with jQuery

I'm trying to replace all my empty select boxes with a text message but it's not working. Here's my jQuery:

var s = $("table.preference select option");
if(s.length == 0){
   s.parents("td").html("No more preferences to add!");
}

I've also tried:

$("table.preference select option").each(function(){
   if($(this).length == 0){
      $(this).parents("td").html("No more preferences to add!");
   }
});

But neither works. I have two select tags in two different tables - I need the jQuery to find any empty select box and replace its table cell with a text message. Does anybody know where I'm开发者_运维技巧 going wrong?


Your first approach will not work if you have at least 1 option-element in one of all select-elements inside the table.

Solution without using $.each():

 $("table.preference select:not(:has(option))")
  .parents("td").html("No more preferences to add!");


Try something like this:

$("table.preference select").each(function(){
   if($(this).children().length == 0) {
      $(this).parents("td").html("No more preferences to add!");
   }
});


Have you tried other selectors? Off the top of my head:

var s =  $("table.preference select:empty");
if(s.length != 0){
   ...
}


Try this:

$("table.preference select").each(function() {
    if ($(this).children("option").length === 0) {
      $(this).parents("td").html("No more preferences to add!");
    }
});

Based on @Kon's suggestion, if you wish to check inside possible optgroup tags as well, you could try this:

$("table.preference select").each(function() {
    if ($("option", this).length === 0) {
      $(this).parents("td").html("No more preferences to add!");
    }
});

That will check for options inside the select itself, as well as inside any optgroups.

Example here: http://jsfiddle.net/UEaQU/1/


This works for me.

  • Detect any Select Box with Empty Options.
  • Filter any div that contains some text "abc"

JSFIDDLE


    $("div>select:not(:has(option))").hide();

$('div').filter(function () {
    if($(this).text().trim().toLowerCase() === 'abc'){
        $(this).hide();
    };
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜