How to validate selected value from many dropdown select? - javascript

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 :)

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.

How to use if statement if you have three drop down selected values using javascript and html

I have three drop down selected values as you can see below.
How can I say for example if car = volvo and color = Black and name = Jone // do something or alert (cool) in JavaScript?
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
<option value="green">green</option>
</select>
<select>
<option value="'mark">'mark</option>
<option value="jones">jones</option>
<option value="james">james</option>
<option value="Vardy">Vardy</option>
</select>
It would have been very easy with angular js by two way binding and applying same valuechange listener on all the three dropdowns.
However, here also you can provide 3 different ids to your dropdowns and bind them with same value-change listener using onchange attribute.
In the value-change listener function , get the value of all the 3 drop down value by document.getElementById , comapre them and display alert accordingly. You can find below the sample solution for it which I prepared:
<head>
<script>
function dropdownChange() {
var car=document.getElementById("car").value;
var color=document.getElementById("color").value;
var owner=document.getElementById("owner").value;
if(car==="volvo" && color==="red" && owner ==="james") {
alert("Cool");
}
}
</script>
</head>
<body>
<select id ="car" onchange="dropdownChange();">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<select id="color" onchange="dropdownChange();">
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
<option value="green">green</option>
</select>
<select id="owner" onchange="dropdownChange();">
<option value="'mark">'mark</option>
<option value="jones">jones</option>
<option value="james">james</option>
<option value="Vardy">Vardy</option>
</select>
</body>

If select option value matches text in separate div, add disabled field

I'm using a select field on my site which reloads the page and then adds this to value to a separate div. I want to be able to disable this option if any of the divs have the same value as the option.
<select id="bayname" name="bayname">
<option value="">--Select Bay--</option>
<option value="1">Bay 1</option>
<option value="2">Bay 2</option>
<option value="3">Bay 3</option>
<option value="4">Bay 4</option>
<option value="5">Bay 5</option>
<option value="6">Bay 6</option>
<option value="7">Bay 7</option>
<option value="8">Bay 8</option>
<option value="9">Bay 9</option>
<option value="10">Bay 10</option>
<option value="11">Bay 11</option>
<option value="12">Bay 12</option>
<option value="13">Bay 13</option>
<option value="14">Bay 14</option>
<option value="15">Bay 15</option>
<option value="16">Bay 16</option>
<option value="17">Bay 17</option>
<option value="18">Bay 18</option>
<option value="19">Bay 19</option>
<option value="20">Bay 20</option>
<option value="21">Bay 21</option>
<option value="22">Bay 22</option>
<option value="23">Bay 23</option>
<option value="24">Bay 24</option>
<option value="25">Bay 25</option>
<option value="26">Bay 26</option>
<option value="27">Bay 27</option>
<option value="28">Bay 28</option>
<option value="29">Bay 29</option>
<option value="30">Bay 30</option>
</select>
For example if a user clicks on 'Bay 1' a div will be created like this:
<li id="1509013949" class="cart-select cart-mode-cart">
1
</li>
And then when the page reloads again, i want to create an if statement so if the value from the select is within one of the divs then it should add it as disabled.
I've had ago at doing this using the code below and i can't get it to print out in the console log.
var baynumberoption = $("#bayname option").val();
var baynumber = $(".cart-select a[href='#select']").text();
if (baynumber.indexOf(baynumberoption) >= 0) {
console.log("match found");
}
$("#bayname option") returns all of the options so I think you really want to use the following. Note if you don't want to rely on the inner text of the link, you can also add data attribute like data-id="1" to store the value which can be used like:
$("#bayname option").each(function() {
var val = $(this).val();
if ( $(".cart-select a[data-id=" + val + "]").length > 0 ) {
$(this).attr("disabled", "disabled");
}
});
Some of the syntax may be off but you get the idea.

iterate through select dropdowns with same class name to find selection of specific option [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to search through a select boxes with same class name, to discover if anyone has selected a specific option...
<select class='myclass' id='instance1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance2'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance3'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script>
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (something == 'audi')
alert("found!");
});
Simply take all selected options with :selected pseudo, and filter them by value. This is cool and clean one liner.
$('.myclass option:selected').filter("[value=audi]")
Afterwards, you can grab this in a variable, and check if length > 0. (so you have a selected audi option).
This way:
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (obj.value() == 'audi')
alert("found!");
});
you may need to use the JS code in a function though :)
$('#check').click(function(){
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (obj.value== 'audi'){
alert("found!");
}else{
alert('Not found');
}
});});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="check">Check</button>
<select class='myclass' id='instance1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance2'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance3'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You will need a button to handle the detection or alternatively you can bind to the select change event handler and handle the newly selected option.
To achieve it via a button click, add the following to your HTML.
<button id="checkSelected">Check for Audi</button>
And then in your JavaScript/jQuery code:
$("#checkSelected").on("click", function() {
$("select[class='myclass'] option:selected").each(function() {
var element = $(this);
if (element.val() === "audi") {
alert('The user has selected an Audi in combobox ' + element.parent().attr("id"));
}
});
});
This will transverse the DOM and select all selected elements for the comboboxes with the class myclass and check if the value is equal to audi and alert the user which box they selected it from.
http://jsfiddle.net/0w0v06et/

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