coffeemonitor
coffeemonitor

Reputation: 13120

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

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

Upvotes: 6

Views: 7092

Answers (7)

Frenchi In LA
Frenchi In LA

Reputation: 3169

How about

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

Upvotes: 2

Mohammad Ali Akbari
Mohammad Ali Akbari

Reputation: 10395

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

Upvotes: 0

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

You can use the not slector like this:

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

Upvotes: 0

eykanal
eykanal

Reputation: 27017

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>

Upvotes: 0

Naftali
Naftali

Reputation: 146310

Try this using jQuery's not() selector

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

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

});

Upvotes: 3

pixelbobby
pixelbobby

Reputation: 4440

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

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100331

Use this selector

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

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

Attribute not equal selector jQuery API

Upvotes: 10

Related Questions