Treat multiple select as single select if the value is selected - javascript

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>

Related

How to track the select option is deselect and and grab the deselect option value in jquery

Below is the example of the code for the scenario.
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>
Suppose if deselect the honda, how would i know that this particular option is deselected and how i will grab that option value in jquery.
Thanks in advance
You can keep some variables and filter out those accordingly.
and in JS, you can handle these variables in the events
Here is the snippet, Hopefully you were looking for the same.
var prevValues = [];
var currentValues = [];
$(document).ready(function() {
currentValues = $('.car').val();
})
$('.car').on('change', function() {
prevValues = [...currentValues];
currentValues = $('.car').val();
let newlyAdded = currentValues.filter(x=> !prevValues.includes(x))[0];
let newlyRemoved = prevValues.filter(x=> !currentValues.includes(x))[0];
if(newlyAdded) {
console.log('Added item', newlyAdded);
}
if( newlyRemoved) {
console.log('Removed Item', newlyRemoved);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>

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.

Change css based in Select option value selected

I have in one form, one selects with one question that if determined value selected I need to display none the next question. How can I make a jquery code that detects that the user selected a determinated option in select and change the CSS of the page?
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
So as far as I understand with your short description you need to do something based on the value selected by user in select box which we call an event onchange.I am writing a code example for you
<select onchange="somefunction($(this).val())">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script>
function somefunction(value){
if(value == 1){
$("body").css("background-color","red");
}
if(value == 2){
$("body").css("background-color","yellow");
}
}
</script>
Your question is a bit vague, but i think this is what your after:
const value = $('#selectID option[value=""]').prop("selected", true);
if (value....") {
// do css stuff
}
Additionally you can get the value / text like so:
<select id="car_manufacturer">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script>
const element = document.getElementById("car_manufacturer");
const value = element.options[element.selectedIndex].value;
const text = element.options[element.selectedIndex].text;
</script>
You could extend on the above with a on onchange event on the select element.
<select id="car_manufacturer" onchange="selectManufacturer(this)">
Manipulate CSS:
JavaScript:
document.body.style.backgroundColor = "red";
jQuery:
$("body").css("background-color","red");
Fiddle
onchange example with css manipulation:
http://jsfiddle.net/9L0czmeq/

How to unselect options in select using jquery

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>

Two HTML selects with differing selected values

I got following HTML code:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
So both of them have same data. I need to secure, that user can't select same value in both of them.
I hoped, that JQuery has some nice feature like:
$("#first").getOptions()
or even
$("#first").setOptions()
but unfortunately, it doesn't. This makes it very complicated for me, because I don't know JQuery very well ...
So, what is the best approach to solve my problem?
You can get the value of the currently selected option by doing:
$('#first option:selected').text();
$('#second option:selected').text();
Assuming I understand your question, you don't want the user to be able to enter the same value in each box. So, something similar to:
$first = $('#first');
$second = $('#second');
$first.on('change', function() {
$second.find('option').attr('disabled', false);
var firstVal = $first.find('option:selected').text();
$second.find('option:contains("'+ firstVal +'")').attr('disabled', true);
});
$second.on('change', function() {
$first.find('option').attr('disabled', false);
var secondVal = $second.find('option:selected').text();
$first.find('option:contains("'+ secondVal +'")').attr('disabled', true);
});
I should probably note that there are ways for you to achieve your getOptions() and setOptions() ideas, you can do $select.find('option') to get the options. For setting them, define some options in html and set the select element's innerHTML to those elements:
var options = '<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>';
$select.html(options);
JSFiddle demo
You can disable single options in your select
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2" disabled>Two</option>
<option value="3">Three</option>
</select>
Handle event onSelect on first select and based on it disable proper <option> in second select
When one is changed, if the other is the same, you could change it back to default, like this.
$(document).on('change', '#first', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#second').val(0);
}
});
$(document).on('change', '#second', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#first').val(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Try this(codepen):
HTML:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Javascript/jQuery:
var strUser;
var strUser2;
$(function() {
$("#first").change(function() {
var e = document.getElementById("first");
strUser = e.options[e.selectedIndex].text;
if (strUser == strUser2) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("first").disabled=true;
} else {
document.getElementById("second").disabled=false;
}
});
});
$(function() {
$("#second").change(function() {
var e = document.getElementById("second");
strUser2 = e.options[e.selectedIndex].text;
if (strUser2 == strUser) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("second").disabled=true;
} else {
document.getElementById("first").disabled=false;
}
});
});
Essentially, this code will retrieve selected values from the dropdowns on change, and then a comparison will be made. If the values are equal, the recently selected dropdown will be disabled. You then will have to select a different value in the other dropdown to re-enable the disabled dropdown. Here's the codepen that displays the working functionality. This will not allow a user to select two of the same values without a dropdown being disable and turned off.

Categories

Resources