Jquery input options select but one

I have a multi-select that contains many sources where the visitor came from. I also enable the option (with the value "all") at the top of all options.

When someone clicks this option, then all options will be selected. And this part is simple. I have included multi-select and jquery that listen for the 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, this works great! For example, jquery also selects the top option.

Is there any way to tell jquery to exclude a single option?

+6
source share
7 answers

Use this selector

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

All parameters in which the attribute value is not all , example on jsFiddle

Attribute not equal to jQuery API selector

+10
source

Try this with jQuery not () selector

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

What about

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

If I understand correctly what you are trying to do, instead I would use a list of checkboxes, and then select everything that checks all the checkboxes, and not on the drop-down list ...

0
source

Avoid the problem; just add disabled to the top option. In any case, you do not want them to be able to send this option.

 <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> 
0
source

You can use the wrong choice:

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

maybe 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
source

Source: https://habr.com/ru/post/887139/


All Articles