multiple select boxes with same options - require unique selection - javascript

I have a form with 3 select boxes. Each select box has the same options. I want to require that you have to select a different option for each select box. For example, let's say the options are "cat", "dog" and "bird". If someone selects "bird" in the first select box, I want to disable or hide that option from the other two boxes. If they change their selection, then "bird" will be enabled or unhidden again.
<select id="box1">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
I assume I can do this with jquery onchange but I'm not sure how to require the unique selection across different select boxes.
$('select').on('change', function() {
// If option is selected, disable it in all other select boxes. If option is deselected, reenable it in all other select boxes.
})
Thanks for your help!

1) Top To Bottom Priority Approach
The flow must be top to bottom. This also means when ever the user changes the dropdown value all the next dropdown's which come after it must be reset. Having said this, here is my code snippet.
HandleDropdowns($('#box1')); //initially call this function to handle the dropdowns by passing the first dropdown as parameter
$('select').on('change', function() {
HandleDropdowns($(this)); // handle all dropdowns on any change event.
});
function HandleDropdowns(element) {
var $element = element;
var value = $element.val();
$element.nextAll().val(''); //using nextAll lets reset all the following dropdowns
$element.nextAll().attr('disabled', 'disabled'); //disable all the following dropdowns.
HandleOptions(); // call this function to toggle the options
if (value.length) {
$element.next().removeAttr('disabled'); // only if this dropdown has some selection enable the next dropdown.
}
}
function HandleOptions() {
$('option').removeAttr('disabled'); //reset all the options to be available
$.each($('select'), function() { //loop from top to bottom and disable the options one by one.
var value = $(this).val();
if (value.length) {
$(this).nextAll().find('option[value="' + value + '"]').attr('disabled', 'disabled');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="box1">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
2) All Select Box With Same Priority Approach
In this approach when ever the user selects a value we check if any other dropdown has the same value, If yes reset it else do nothing. Below is a working sample.
$('select').on('change', function() {
HandleDropdowns($(this));
});
function HandleDropdowns(element) {
var $element = element;
var value = $element.val();
$.each($('select').not($element), function() { //loop all remaining select elements
var subValue = $(this).val();
if (subValue === value) { // if value is same reset
$(this).val('');
console.log('resetting ' + $(this).attr('id')); // demo purpose
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="box1">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>

Try this
$('select').on('change', function () {
$("select").find("option").removeAttr("disabled");
$("select").not(this).find("option[value=" + $(this).val() + "]").attr("disabled", "disabled");
});

You can use onchange listener and evaluate the results simultaneously. Also add an reset button cause once three get selected, it becomes bottle neck case.
The working code is given below
function changeSelect(elements) {
var values = {};
elements.forEach(function(item){
values[item.id] = item.value;
});
elements.forEach(function(item){
for(var i = 0; i < item.children.length; i++) {
for(ids in values) {
if(item.id != ids && item.children[i].value == values[ids]) {
item.children[i].style.display = 'none';
}
}
}
});
}
function resetSelection(elements) {
elements.forEach(function(item){
item.value = '';
for(var i = 0; i < item.children.length; i++) {
item.children[i].style.display = '';
}
});
}
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var box3 = document.getElementById('box3');
var boxArray = [box1, box2, box3];
boxArray.forEach(function(item){
item.addEventListener('change', changeSelect.bind(undefined,boxArray));
});
document.getElementById('reset').addEventListener('click', resetSelection.bind(undefined,boxArray));
<select id="box1">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<button id="reset">Reset</button>

Related

JavaScript check if dropdown options are all disabled

I have a dropdown menu with all options disabled except the first one which has no value (just a label). How can i check on $(document).ready(function() if all options of this dropdown option are disabled (except the first option which has no value) and if so show an alert for example alert ('All Options Disabled');.
<!DOCTYPE html>
<html>
<body>
<select id="selectId">
<option value="">Select a Car</option>
<option value="volvo"disabled>Volvo</option>
<option value="saab"disabled>Saab</option>
<option value="opel"disabled>Opel</option>
<option value="audi" disabled>Audi</option>
</select>
</body>
</html>
Iterate over the options and check to see if every option is either disabled or whose value property is the empty string:
const allDisabled = Array.prototype.every.call(
document.querySelector('#selectId > option')
option => option.disabled || option.value === ''
);
console.log(allDisabled);
<select id="selectId">
<option value="">Select a Car</option>
<option value="volvo"disabled>Volvo</option>
<option value="saab"disabled>Saab</option>
<option value="opel"disabled>Opel</option>
<option value="audi" disabled>Audi</option>
</select>
Or, with jQuery and each:
let allDisabled = true;
$('#selectId > option').each(function() {
const $this = $(this);
if (!$this.prop('disabled') && $this.prop('value')) allDisabled = false;
});
console.log(allDisabled);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectId">
<option value="">Select a Car</option>
<option value="volvo"disabled>Volvo</option>
<option value="saab"disabled>Saab</option>
<option value="opel"disabled>Opel</option>
<option value="audi" disabled>Audi</option>
</select>

HTML select option VALUE calculate

I am trying to make a simple "registry book" from a select HTML
The idea is 3 selecting options click confirm and based on the selected options make a price with a math formula or (don't know what is ) an array (in the sense of a table of like every var there) add a Hour:Minute from machine and place it in a paragraph.
It will work. (just learning HTML and CSS)
Math would be select2 * select3 with one exception in the case of [select2(option1 and option2) * select3 = samevalue)
With that aside can someone post a modular simplistic type of code that would Help.
For those who need to read some more:(copy&paste* - *Sorry for indentation)
document.getElementById("Confirm").onClick = function() {
var entry = ""
document.getElementById("Televizor").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Controllere").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Timp").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Table").innerHTML = "<br> " + entry + Date();
var entry = ""
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controller">
<option value="0">Controllere</option>
<option value="1c">1 Controller</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="Confrim)">Confirm</button>
</div>
<p id="Table"></p>
Well, you could start off by making sure the spelling and capitalization of your IDs and function names match.
Also, you should create some form of a validation method to check if all the fields are valid before proceeding to the calculation method.
Not sure what you are multiplying, but if you can at least get the valuse from the form fields, that's half the battle.
You should also enclose all your fields within a form object so you can natively interact with the form in a traditional HTML fashion.
// Define the confirm clicke listener for the Confirm button.
function confirm() {
// Grab all the fields and apply them to a map.
var fields = {
'Televizoare' : document.getElementById('Televizoare'),
'Controllere' : document.getElementById('Controllere'),
'Timp' : document.getElementById('Timp')
};
// Determine if the user selected an option for all fields.
var isValid = doValidation(fields);
if (!isValid) {
document.getElementById("Table").innerHTML = 'Please provide all fields!';
return;
}
// Create listeners ???
fields["Televizoare"].onChange = function(e) { };
fields["Controllere"].onChange = function(e) { };
fields["Timp"].onChange = function(e) { };
// Set the value of the paragraph to the selected values.
document.getElementById("Table").innerHTML = Object.keys(fields)
.map(field => fields[field].value)
.join(' — ');
}
// Validation function to check if ALL fields have options selected other than 0.
function doValidation(fields) {
return [].every.call(Object.keys(fields), field => fields[field].selectedIndex !== 0);
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controllere">
<option value="0">Controllere</option>
<option value="1c">1 Controllere</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="confirm()">Confirm</button>
</div>
<p id="Table"></p>

FadeIn fadeOut depending upon the previous option value in select [duplicate]

I have 4 Drop Downs.
Each drop by default has a --select-- option. Each box has a unique id. As you can see, the second drop down is disabled if the above drop down value is --select--. It will only enable when the value is anything but --select--
Here's my code:
$(document).ready(function() {
$('#idOfTheFirstDropDown').bind('change', function() {
var options = $(this).children('option');
var item = $('div.c-select').children().hide(); // hide all the elements
var value = Math.floor(Math.random() * options.length );
//console.log(value);
if (value.length) { // if selected
item.show(); // show the next dropdown
}
}).trigger('change');
});
I want it to show the next dropdown only when my previous drop down value is not --select--. My code is taking in the first drop down but not changing the value. What am I doing wrong? Thanks.
My HTML for one drop down box. Only the ID's change for the remaining 3. Rest of the HTML remains the same.
<div class="c-select">
<select name="list1" onchange="javascript:setTimeout('__doPostBack(\'list1\',\'\')', 0)" id="idOfTheFirstDropDown" class="GroupDD dropDown ">
<option selected="selected" value="">-- Select --</option>
<option value="1">Group1</option>
</select>
</div>
Rather than hiding the options, I would use the disable attribute (comments in code):
var selects = $('.drop-down');
selects.not(':eq(0)').prop('disabled', true); // disable all but first drop down
selects.on('change', function() {
var select = $(this),
currentIndex = selects.index(select),
nextIndex = currentIndex + 1;
// only do this if it is not last select
if (currentIndex != selects.length - 1) {
selects.slice(nextIndex) // get all selects after current one
.val('') // reset value
.prop('disabled', true); // disable
selects.eq(nextIndex).prop('disabled', select.val() === ''); // disable / enable next select based on val
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Check this one;
HTML code:
<select id="sel-1"></select>
<select id="sel-2"></select>
<select id="sel-3"></select>
<select id="sel-4"></select>
JS Code:
$(document).ready(function(){
$("[id^=sel]").change(function(){
/*
* find out the current box id
*/
var id=$(this).attr("id");
/*
* find out the current box id order number
*/
var ordernumber=id.split("-")[1];
if($(this).val()!="select")
{
//enable next one
$("#sel-"+(ordernumber+1)).show();
}
})
})
Assuming the option that has '--select--' as text has no value, just use val on the handler to check if the selected option is other than the empty
if(this.val() !== '') {
// enable following select
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
select {
margin: 5px 0;
display: block;
}
</style>
<script>
$(function() {
$('.cls-select').change(function() {
if ($(this).val() == '--select--') {
// reset and disable the next drop downs
$('.cls-select:gt(' + $('.cls-select').index($(this)) + ')').val('--select--').prop('disabled', true)
} else {
// current drop down has value so enable the next drop down
$(this).next().prop('disabled', false);
}
});
})
</script>
<select class="cls-select">
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>

Javascript auto select from dropdown

I'm searching and searching and can not find anything exactly what I need.
So I need javascript, that will select option from dropdown, but not by the option value number, but name.
I have:
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
So I need to select • Jawor by name, not by id - it's the most important. How do I make it work?
For you is it like;
var options = document.getElementsByClassName("aa")[0].options,
name ="Jawor";
for(i = 0; i < options.length; i++){
if(options[i].text.indexOf(name) > -1){
options[i].selected = true;
break;
}
}
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
U need to Use onChange Event Handler ... for example
<select onchange="showSelected()">
Then write your script ...
<script>
function showSelected(){
var s=document.getElementById('local'); //refers to that select with all options
var selectText=s.options[s.selectedIndex].text // takes the one which the user will select
alert(selectText) //Showing the text selected ...
}
</script>
Rest of your code is okay !
<select class="aa" id="local" name="local" onchange='showSelected'()>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
Using jquery here. You can use the following function:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
}
})
}
A demo:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
return false;
}
})
}
//use the function
setTimeout(function() {
selectFromDropdown('#local', '• Dzierżoniów')
}, 1000)
setTimeout(function() {
selectFromDropdown('#local', '• Jawor')
}, 4000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="aa" id="local" name="local">
<option value="">Select</option>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
for chrome console use this
document.getElementById("id").selectedIndex = '3'; or
document.getElementById('id').value = 'BA';

Shopify Drop down Validation

I'm building a web store on shopify. I want to add a validation to dropdown that if no size/value is selected from drop down, it automatically select 1st size/value. when we click on add to cart button.
Thanks for the help.
Given this HTML:
<select id="drop">
<option value="0">Please select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<button id="add">Add to cart</button>
Use this javascript/jQuery:
$(document).ready(function() {
var $drop = $("#drop");
$("#add").on("click", function() {
if($drop.val() == 0) {
$drop.val(1);
}
});
});
http://jsfiddle.net/82vrccem/1/
Here I have mention a drop-down list and after that the JavaScript validation also given.
<select id="dropdown">
<option value="0">Select</option>
<option value="1">Option One</option>
<option value="2">Option Two</option>
<option value="3">Option Three</option>
</select>
Use the flowing JavaScript validation for upper drop-down list.
function Validate()
{
var e = document.getElementById("dropdown");
var strUser = e.options[e.selectedIndex].value;
//if you need text to be compared then use
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0) //for text use if(strUser1=="Select")
{
alert("Please select a user");
}
}

Categories