开发者

jquery select input options, except one

I have a multi-select that holds many sources for whence a visitor came. I am also including an option (with the value of "all") in the top of all the options.

When someone clicks that option, then all the options will be selected. And that part is easy. I've included the multi-select and jquery that listens for a click event.

<select name="sourceid[]" id="sourceid" style="width:230px;" multiple="multiple">
  <option value="all">-- Select All Sources --</option>
  <option value="1">Internet</option>
  <option value="2">Radio</option>
  <option value="3">Phone</option>
  <option value="4">Other</option>
</select>


$("#sourceid").click(function(){

  if($(this).val()=='all'){ $("#sourceid option").attr("selected","selected"); }

});

So far it works gre开发者_Python百科at! The jquery will also select the top option, naturally.

Is there a way to tell jquery to exclude selecting that one option?


Use this selector

$("option[value!=all]")

All options where the attribute value is not all, example on jsFiddle

Attribute not equal selector jQuery API


Try this using jQuery's not() selector

$("#sourceid").click(function(){

  if($(this).val()=='all'){ 
            $("#sourceid option").not(this)
                   .attr("selected","selected"); 
  }

});


How about

$("#sourceid option").not(':first').attr("selected","selected");


If I understand correctly what you're trying to do, I would use a checkbox list instead and then have a select all that checks all the boxes instead of using a dropdown...


Avoid the problem; just add disabled to the top option. You don't want them to be able to submit that option, anyway.

<select name="sourceid[]" id="sourceid" style="width:230px;" multiple="multiple">
  <option value="all" disabled>-- Select All Sources --</option>
  <option value="1">Internet</option>
  <option value="2">Radio</option>
  <option value="3">Phone</option>
  <option value="4">Other</option>
</select>


You can use the not slector like this:

 $("#sourceid :not(option[value='all'])").attr("selected", "selected");


$("#sourceid option[value=all]").click(function(){
    $(this).siblings().attr("selected","selected");
});

maybe its better:

$("#sourceid option[value=all]").click(function(){
if($(this).siblings("[selected=selected]").size() == $(this).siblings().size()) {
    $(this).siblings().removeAttr("selected");
} else {
    $(this).siblings().attr("selected","selected");
}
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜