6

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 great! The jquery will also select the top option, naturally.

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

1
  • You better use change instead of click. This ill also capture selects with the keyboard. May 2, 2011 at 18:54

7 Answers 7

10

Use this selector

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

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

Attribute not equal selector jQuery API

3

Try this using jQuery's not() selector

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

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

});
0
2

How about

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

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...

1
  • Yes, that's an option. This is simply a preference I'm asking. May 2, 2011 at 18:56
0

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>
1
  • True! it does stop jquery from recognizing the click event, unfortunately. May 2, 2011 at 18:55
0

You can use the not slector like this:

 $("#sourceid :not(option[value='all'])").attr("selected", "selected");
0
$("#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");
}
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.