Multiple select, when one certain option is selected, unselect other options - javascript

I have a multiple select list in my HTML. If value 296 gets selected, all the other options must get unselected.
This is the code I am using so I don't have to use CTRL when I want to select multiple options:
$("#select").mousedown(function(e) {
e.preventDefault();
var select = this;
var scroll = select.scrollTop;
if (select.value == 296) {
//unselect all the other options
}
e.target.selected = !e.target.selected;
setTimeout(function() {
select.scrollTop = scroll;
}, 0);
$(select).focus();
}).mousemove(function(e) {
e.preventDefault()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">
<option value="296">Primairadres </option>
<option value="297">Bezoekadres </option>
<option value="298">Factuuradres </option>
<option value="299">Postadres </option>
</select>
I can't seem to figure out how I can unselect all the other options when value 296 is selected

The below seems to achieve what you state above. It does also stop you selecting the options if 296 is already selected as well.
const unselect = '296'
$('#select').change(function() {
const $el = $(this)
console.log($el.val())
if ($el.val().indexOf(unselect) !== -1) {
$el.children('option').each(function() {
$opt = $(this)
if ($opt.val() !== unselect) {
$opt.prop('selected', false)
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">
<option value="296">Primairadres </option>
<option value="297">Bezoekadres </option>
<option value="298">Factuuradres </option>
<option value="299">Postadres </option>
</select>

Related

How to allow the selection ONLY one option for certain values in a multiple selection dropdown list?

I want to make a dropdown menu with the following options. I want be able to select a select multiple value for option A, B, and C, but disable multiple selection if option D is selected. How can I do that? Thanks.
<label>Choose an option:</label>
<select required multiple>
<option>Please select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">C</option>
</select>
Remove the other selected options if "D" is selected, otherwise allow multiple select (do nothing).
document.addEventListener("mouseup", checkMultiple);
function checkMultiple(evt) {
const selectr = evt.target.closest(`select`);
if (selectr && selectr.querySelector(`[value='D']:checked`)) {
[...selectr.options].forEach(v => v.selected = v.value === `D`);
}
}
/*
Note: the above is a shortened version of
the function in the original answer:
function checkMultiple(evt) {
if (!/option/i.test(evt.target.nodeName)) {
return true;
}
const selector = evt.target.parentNode;
const options = [...selector.querySelectorAll("option")];
if (options.find(v => v.value === "D").selected) {
options
.filter(v => v.value !== "D")
.forEach(v => v.selected = false);
}
}
*/
<label>Choose an option:</label>
<select required multiple>
<option>Please select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
let arr = [];
document.querySelector('#product_attr_ids').onchange = function(e) {
if (this.querySelectorAll('option:checked').length <= 1) {
arr = Array.apply(null, this.querySelectorAll('option:checked'));
} else {
Array.apply(null, this.querySelectorAll('option')).forEach(function(e) {
e.selected = arr.indexOf(e) > -1;
});
}
}
<p>The html of selections with multiple set to true.</p>
<p>Pressing command + click will not allow you to choose more than one option</p>
<p>Javascript. You can chnage the <strong>('option:checked').length <= 1) </strong> to whatever number you want, peraps you want your users to choose only 2 or 3 options.</p>
<label>Choose an option:</label>
<br />
<select id="product_attr_ids" required multiple>
<!-- Prevent user from select first blank option -->
<option disabled>Please select</option>
<option value="A">Attribute 1</option>
<option value="B">Attribute 2</option>
<option value="C">Attribute 3</option>
<option value="D">Attribute 4</option>
</select>

How to deselect values from multiselect option using jQuery?

I have a multiselect option. If i select Mahesh & Dilip both, I want to show a pop up message that you can not select both at a time. If I click Ok on pop up then I want to deselect ONLY these two. How to do this? Here is my code:
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>
<script type="text/javascript">
$('#playerNames').on('change',function(){
var selected = $('#playerNames:selected').map(function(){return $(this).val();}).get();
alert(selected.length);
if(jQuery.inArray("Mahesh", selected) !== -1){
var maheshSelected = true;
}
if(jQuery.inArray("Dilip", selected) !== -1){
var dilipSelected = true;
}
if(maheshSelected == true && dilipSelected == true){
var alertMessage = "You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.";
alert(alertMessage);
if (confirm(alertMessage)) {
//code to deselect both
}
}
});
You can select the options using $('option:contains(Mahesh), option:contains(Dilip)') and deselect them using .prop('selected', false):
$('#playerNames').on('change', function(){
const selected = $('#playerNames :selected').map(function() {return $(this).text()}).get()
if (selected.includes('Mahesh') && selected.includes('Dilip')) {
alert('You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.')
$('option:contains(Mahesh), option:contains(Dilip)').prop('selected', false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>
Here's a cross-browser solution (works on Internet Explorer 9+):
$('#playerNames').on('change', function(){
var selected = $('#playerNames :selected').map(function() {return $(this).text()}).get()
if (selected.indexOf('Mahesh') > -1 && selected.indexOf('Dilip') > -1) {
alert('You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.')
$('option:contains(Mahesh), option:contains(Dilip)').prop('selected', false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>

Multiple select elements - Handle with jQuery when select an option from all of them

I have two select elements with some options. What I want to do is to handle this with jquery so as I can get the values of them only when options have values.
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
If I want to handle with one select element only I use .on('change', function() with select element and it works, but with multiple select element how can I do it.
You should check if selectedIndex is not 0 for all your select elements.
$(document).on('change', 'select', function () {
var allChanged = true;
// check if there is any other select element which was not changed
$('select').each(function () {
if (this.selectedIndex == 0) {
allChanged = false;
}
});
// if all select elements have been changed
if (allChanged) {
alert('BOTH CHANGED');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
Just a side note, use .filter() :
$('select').change(function() {
var m = $(this).siblings('select').addBack();
var n = m.filter(function(){
return $(this).val() == null && $(this)
});
if ( !n.length ) alert('both selected')
});
DEMO

Compare select values and show alert if they match

I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!
Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>
I used the same class on all the dropdowns and then use only one event handler.
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.

JavaScript - Hide buttons depending on the options selected

I have two (or in some places more) dropdowns (select) with several options. There is also a button for clearing all selected values in dropdowns. There is one aspect of this clearing button that does not working properly for my needs.
The button is displayed only if dropdowns has selected option with value, after is selected options with empty value, button is hidden. After i choose some option in both dropdowns (button displayed) and then change value in one from this dropdowns to option without value (button is hidden). Problem is, that button is hidden after one from dropdowns has empty value.
I need that button to be hidden only if all dropdowns have a selected option with an empty value. This jsfiddle illustrates what I mean.
I use select2.js for the dropdowns.
HTML:
<input type="button" class="opt-clear" value="Clear all dropdowns">
<div class="option">
<select>
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div class="option">
<select>
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
Javascript:
$('select').select2();
$('.option select').change(function() {
var id=$(this).val();
if (id=="") {
$(".opt-clear").hide();
} else {
$(".opt-clear").show();
}
}).trigger('change');
$(".opt-clear").click(function() { $(".option select").select2("val", ""); });
You have to check the val from all lists. If at least one them has a value then dont hide the button. You have to use each() and a var as a flag.
Try:
$('.option select').change(function () {
var flag = 1;
$(".option select").each(function (index) {
var id = $(this).val();
if (id != "") {
flag = 0;
}
});
if (flag) {
$(".opt-clear").hide();
} else {
$(".opt-clear").show();
}
}).trigger('change');
DEMO
Use this code your problem will be solved:
HTML Code :
<input type="button" id="btnChangeddValue" onclick="ddChangeValue();" style="display: none;"
class="opt-clear" value="Clear all dropdowns">
<div class="option">
<select id="dd1" onchange="ddChange(this.value);">
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div class="option">
<select id="dd2" onchange="ddChange(this.value);">
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
Js Script :
function ddChange(ddValue) {
if (ddValue != "" && ddValue != null) {
// $('#btnChangeddValue').css({ 'display': 'block' });
document.getElementById('btnChangeddValue').style.display = 'block';
}
else {
document.getElementById('btnChangeddValue').style.display = 'none';
}
}
function ddChangeValue() {
document.getElementById('dd1').value = "";
document.getElementById('dd2').value = "";
document.getElementById('btnChangeddValue').style.display = 'none';
}
Reguards,
Hardik Patel
hi I would try to get all the select with value. if their count is greater than 0 than button should be displayed. you can achieve that with jquery filter funstion
if ( $('.option select').filter(function(0 { return $(this).val != ''; }).length > 0){
//show button
}
else{
//hide button
}
Updated your fiddle.
$('.option select').change(function() {
checkvalue();
if(flag){
$('input').show();
}else{
$('input').hide();
}
}).trigger('change');
function checkvalue(){
$('.option select').each(function(){
if ($(this).val()!="") {
flag = true;
}else{
flag = false;
}
});
}
Your DOM has multiple select tags. So your code did not work.

Categories

Resources