How to unselect options in select using jquery - javascript

Below is my HTML. I have given multiple option elements in the select tag.
<select class="car" multiple size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I am able to multi-select by holding the CTRL key. I am able to retrieve the selected values using the following jQuery
$.each($(".car option:selected"), function() {
countries.push($(this).val());
});
How can I unselect the value using jQuery? The selected value will be highlighted as shown:
Thanks in advance

Set the selected property to false: $(selector).prop('selected', false).
I have added a button and attached a click event to be able to demonstrate.
var countries = [];
function unselect() {
$.each($(".car option:selected"), function () {
countries.push($(this).val());
$(this).prop('selected', false); // <-- HERE
});
}
$("#unselect").click(unselect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="car" multiple size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" value="unselect" id="unselect" />

You can use $('.car').val([]); for unselect all options in multi-select dropdown.
For multi select value you can pass empty array for unselect all
options.
$(document).ready(function(){
$("#select").click(function(){
var values= [];
$(".car > option").each(function(){
values.push($(this).attr('value'));
});
$('.car').val(values);
});
$("#unselect").click(function(){
$('.car').val([]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="car" multiple size="3">
<option value="volvo" selected>Volvo</option>
<option value="saab" selected>Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button id="select">Select All</button>
<button id="unselect">Unselect All</button>
</button>

Related

How to force a select to keep always the same selected value

Let's say we have multiple forms, each form has 40 selects, the ids of each select have the following structure:
#id_form-X-{field_name}
Let's say for example, of those 40 selects, we want 3 of them to be unmodifiable for each form when we change the value of the select, so it will always show the same selected value.
The 3 selects we want to change have the following field_name: ps2_0, ps2_1 and ps2_3.
So I'm looking for a generic solution that works for:
id_form-0-ps2_0
id_form-0-ps2_1
id_form-0-ps2_3
id_form-1-ps2_0
id_form-1-ps2_1
id_form-1-ps2_3
id_form-N-ps2_0
id_form-N-ps2_1
id_form-N-ps2_3
...
...
...
Dummy example:
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
If, for example, the user clicks on the select and selects, for example Saab, the select will show again the value selected by default: Volvo.
I cannot use the 'readonly' or 'disabled' properties for the selects.
What I've tried so far:
$(document).ready(function() {
var previous = "initial prev value";
$("select").on('click', function () {
previous = $(this).val();
}).change(function() {
$(this).val() = previous;
});
});
I'm trying to 'force' the changed select to keep the previous value but didn't work.
Simple Solution
Reset the value of select with initial value on change.
const selectDD = document.getElementById('cars');
const selectedNode = selectDD.value;
selectDD.onchange = (e) => {
selectDD.value = selectedNode;
}
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Much Generic Solution
There should be some unique identifier to differentiate between nodes that can be changed and those to be kept unchanged. Here I have added an unchanged custom attribute to select. Pick thode nodes with that custom attribute and on change of that select, reset its value to initial value.
Example
const selectDD = document.querySelectorAll('[unchanged]');
selectDD.forEach((node) => {
node.attributes.initialValue = node.value;
node.onchange = (e) => {
e.target.value = node.attributes.initialValue;
}
})
You cant change this
<select name="cars" id="cars" unchanged>
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
You cant change this
<select name="gender" id="gender" unchanged>
<option selected value="male">Male</option>
<option value="female">female</option>
</select>
<br/>
You can change this
<select name="age" id="age">
<option selected value="10">10</option>
<option value="15">15</option>
</select>
If you use querySelectorAll to generate a nodelist of all the select menus you could assign a default attribute( using dataset here for instance) and set the value within an event listener so that this default attribute is always selected
document.querySelectorAll('form select').forEach( sel => {
sel.dataset.def=sel.options[sel.selectedIndex].value;
sel.addEventListener('change',function(e){
this.value=this.dataset.def
})
})
<form>
<select name='cars'>
<option selected value='volvo'>Volvo
<option value='saab'>Saab
<option value='mercedes'>Mercedes
<option value='audi'>Audi
</select>
<select name='fruit'>
<option selected value='apple'>Apple
<option value='banana'>Banana
<option value='mango'>Mango
<option value='plum'>Plum
</select>
</form>
Maintain an object which specifies the restricted Select items and the indexes they should always defaults to
let allowedIndexes = {
cars: 0,
bikes: 1
}
function preventChange(e) {
if (Object.keys(allowedIndexes).includes(e.currentTarget.id)) {
let fixedIndex = allowedIndexes[e.currentTarget.id];
e.currentTarget.selectedIndex = fixedIndex;
}
}
<select name="cars" id="cars" onChange="preventChange(event)">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="bikes" id="bikes" onChange="preventChange(event)">
<option value="honda">honda</option>
<option selected value="kavasaki">kavasaki</option>
<option value="suzuki">suzuki</option>
<option value="yamaha">yamaha</option>
</select>
It's somewhat uncomfortable when one's answer is copied.

Treat multiple select as single select if the value is selected

I have this code
$(document).on('change','.custom-select', function(){
var list = [];
$('option:selected', $(this)).each(function() {
list.push($(this).val());
});
$(this).find('option').removeAttr("selected");
console.log(list);
})
What I want to achieve is that if the selected value if "Public", it should unselect all and select only public. Only "Public" should be treated as a single select. Rest of the options can be dynamic. What am I doing wrong?
Using prop('selected', false)
$(document).on('change','.custom-select', function(){
if($('[value="Public"]', this).is(':selected')) {
$('option:not([value="Public"]):selected', this).prop('selected', false)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="custom-select" multiple>
<option value="Public">Public</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

How to validate selected value from many dropdown select?

Example we have this 3 select tags.
select#1 -> Audi
select#2 -> Saab
select#3 -> Audi
so how to check validate all selected value from all select tags while we update it or select it ? and how to prevent it from submit?
HTML
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
<select>
<option value="volvo">Volvo</option>
<option value="saab" selected>Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
You can use jQuery this for getting the validation part. First get the new value which is selected then check with other select tags for their values if it match then trigger duplicate.
Here is a sample JSFiddle
$("select").change(function(){
var newVal = $(this).val();
$(this).siblings().each(function(){
if($(this).val() == newVal)
{
alert("duplicate");
}
});
});
-Help :)

Javascript - show TextField when select choice is

I'm new in JavaScript and I have following issue.
In my HTML code is ordinary SELECT
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
I need to show TextFied under the SELECT only when user select choice Audi.
<input type="text" name="something">
What is the best way to do that?
Start using JQuery (JQuery).
Here is the javascript:
$(document).ready(function(){
// On Select option changed
$("#someId").change(function(){
// Check if current value is "audi"
if($(this).val() === "audi"){
// Show input field
$("#textInputId").show(); //This changes display to block
}else{
// Hide input field
$("#textInputId").hide();
}
});
});
Here is the HTML
<select id="someId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" style="display:none;" id="textInputId" name="someName"/>
Here is the example on JSFiddle:
EXAMPLE
Do this:
<select id="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="hidden" id="txt" name="something">
And do something like this:
select.onchange=function(){
if(select.value=="audi"){
txt.type="text";
}
}
Demo:http://jsfiddle.net/943xQ/
you can achieve it easily using jquery like this:
here is the Html:
<select id="cars">
<option value="-1">Select One</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
and text field:
<input type="text" name="something" id="txtCar" style="display:none;">
$('select#cars').change(function(){
if($(this).val() == "audi")
{
$('input#txtCar').show();
}
});
Here is the DEMO
Place this at the bottom of the page (provided you already have included jquery into this page):
<script>
$('select').change(function () {
if ($(this).val() == 'audi') {
$(this).parent().append('<input type="hidden" name="something">');
}
});
</script>
You can attach the onchange event at select tag and can perform the action you want. Something like
HTML
<div id="result">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
JS
var select = document.getElementById("mySelect");
select.addEventListener("change", function() {
if(this.options[this.selectedIndex].value == 'audi'){
var input = document.createElement('input');
input.type="text";
input.id="txt";
input.name="something";
document.getElementById('result').appendChild(input);
}
});
DEMO
Given the posted HTML, in which you use no specific identifiers (class or id) to identify the relevant elements, and given that you've not specified the availability of any JavaScript library, I'd suggest the following 'plain' JavaScript solution:
function showInputWhen(evt,val){
var el = evt.target;
el.nextElementSibling.style.display = el.value.toLowerCase() == val.toLowerCase() ? 'inline-block' : 'none';
};
var selectEl = document.querySelector('select');
selectEl.addEventListener('change', function(e){
showInputWhen(e,'audi');
});
JS Fiddle demo.
References:
ChildNode.nextElementSibling compatibility.
document.querySelector() compatibility.
EventTarget.addEventListener() compatibility.

jQuery fire event on all dropdowns with specific class

I've got a load of dropdowns on a html page and I want to fire events when they change (eventually it'll be updating all of the dropdowns with content through ajax) - but for now i'm just trying to make it alert out the data element i've selected. I don't want it to fire on every drop down on the page, just the ones with the corresponding css class. I.e. group1 group2. The groups will have to be dynamic too as I don't know how many there could be.
http://jsfiddle.net/6BakA/
Theres a js fiddle above with how it is at the moment. I expect it to only alert 4 times the when you change one of the first 4 dropdowns and only twice when you do the second. But clearly i'm doing something wrong!
My html is:
<select id="test1" class="group1" data-type="Select Box 1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 4">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 5">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 6">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
My JS is:
$(document).ready(function() {
$('select').change(function() {
$('.group1').each(function() {
alert($(this).data('type'));
});
$('.group2').each(function() {
alert($(this).data('type'));
});
});
});
You can do it like this
$(document).ready(function() {
$('select').change(function() { // <-- bind events to all selects
$('.'+$(this).attr('class')).each(function(){ // <-- iterate through each element that has same class
// you don't need to know the class - just use the current element's class that triggered the event
alert($(this).data('type'));
// do what you need to here
});
});
});​
http://jsfiddle.net/wirey00/6BakA/4/
Or even better since you don't know how many selects there'll be, delegating the event will be more efficient since the parent element will be listening and handling the event. You can replace body with any parent element of the select boxes that's available when the dom is loaded
$('body').on('change','select',function(){
$('.'+$(this).attr('class')).each(function(){
alert($(this).data('type'));
// do what you need to here
});
});
http://jsfiddle.net/wirey00/6BakA/5/
You should do it like this:
$(document).ready(function() {
$('select.group1').change(function() {
$('.group1').each(function() {
alert($(this).data('type'));
});
});
$('select.group2').change(function() {
$('.group2').each(function() {
alert($(this).data('type'));
});
});
});

Categories

Resources