prevent options from being selected multiple times - javascript

I have a form that contains 5 select elements and each one has the same options as the others, now I want each option to be selected only once so i need the code to achieve the following:
when a user select some option in one of the select elements that option should be deleted or disabled in the other select elements
when the user change his selection the old option should be added again to the other select elements or re-enabled so that the user can select it in another select
I've achieved both of these but my code only works for 2 selects but if i add more selects when the user change the select number 3 or higher the old options will be enabled in lower selects
My code:
<!DOCTYPE html>
<html>
<head>
<script>
function updateDepartments2(event){
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
if (node !== event.target){
for (child of node){
if (child.index != event.target.selectedIndex || child.index == 0){
var disabledState = ""
}else{
var disabledState = "disabled"
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex)
{
node.selectedIndex = 0
}
}
}
}
</script>
</head>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script type="text/javascript">
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
node.onchange=updateDepartments2
}
</script>
</body>
</html>

First add all the selected options from all the checkboxes in an array.
Then traverse every option in other select box and see if value exists.
Here's the updated js function for it.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (node of selectNodes) {
var opt = node.options[node.selectedIndex].value;
x.push(opt);
}
for (node of selectNodes) {
if (node !== event.target) {
for (child of node) {
if (x.includes(String(child.index))) {
var disabledState = "disabled"
} else {
var disabledState = ""
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex) {
node.selectedIndex = 0
}
}
}
}
Updated fiddle
https://jsfiddle.net/se1dofzb/1/
Update 2 :
I have reworked your function from scratch and please check for any bugs or clarification needed.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (var node of selectNodes) {
if (node.selectedIndex != 0)
x.push(node.selectedIndex);// Add index of all selected elements
}
for (var node of selectNodes) {
for (var child of node) {
//Traverse all option in every select box
var disabledState;
if (x.includes(child.index)) {
//If it is selected, disable it
disabledState = "disabled"
} else {
disabledState = ""
}
node[child.index].disabled = disabledState
}
}
}

Call the function on change of the select and get the option index. Get all the select elements and disable the selected option in the select elements
function a(e)
{
console.log(e.selectedIndex)
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
if(k[i]!=e)
k[i].options[e.selectedIndex].setAttribute("disabled","disabled")
}
}
function d()
{
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
var c=k[i].querySelectorAll('option');
for(let i=0;i<c.length;i++)
c[i].removeAttribute("disabled")
}
}
<!DOCTYPE html>
<html>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<input type="button" onclick="d()" value="Reset">
</body>
</html>

Related

Reset select dropdown base on hierarchy

<script>
function refresh()
{
document.forms[0].submit();
}
</script>
<select name = "firstoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "1">1</option>
if($_POST['firstoption]!= "")
<select name = "secondoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "2">2</option>
if($_POST['secondoption]!= "" && $_POST['firstoption]!= "")
<select name = "thirdoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "3">3</option>
if($_POST['thirdoption]!= "" && $_POST['secondoption]!= "" && $_POST['firstoption]!= "")
<select name = "fourthoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "4">4</option>
Hi,
I have 6 static dropdowns. (something like this for some reason I am currently having laptop problems so I could not copy and paste the code where I wrote down generic values)
DELETED (NO LONGER AN ISSUE FIX ON MY OWN)
Basically, I need 6 dropdown (all values kept after it s refresh) and when a dropdown values changes all of the dropdowns below it get reset.
EDIT:
I am looking for code to reset select option back to the default select option (base on hierarchy). Once an select option above it gets change. so if select "2" gets change select 3,4,5 6 value should change to default option. If select "4" gets change select 5,6 would be change to default option etc.
I do not want ajax or jQuery. I am looking for a solution with php, javascript, or html. I think the way to approach it is by comparing the previous and new index number of the select option being change
Note the code I provide is sudo code I can not copy and paste code due to current laptop state.
So the answer does not need to use my code.
I just want a php/javascript/html code that has multiple select options (4-6 select with 2 option in each) the other drop down will be disable until the select above get a value. SO option 2-6 will be disable until select 1 is pick then option 3-6 will be disable until a value for option 2 is pick).
If he user changes select 1 option will select 2-6 already have a value. Select 2-6 automatically switches to default option value. and option 3-6 is now disable until user select option for select 2
Also stack overflow does not allow bounty to be given until 24 hours so I can not give bounty until tomorrow around this time.
Some suggestions to facilitate the solution:
Give all your drop-down lists the same class attribute.
Use just one change event handler on a container element (or the whole document), and let the handler find out which select value was changed.
Create a function that, given an index, will clear all dropdowns from that index onwards, and will disable all of those, except the first one (at that index).
Call this function in the event handler, and also at page load, so to initialise the enabled/disabled status of those dropdowns.
Below is how that could work. I removed all HTML that is not necessary for this solution, but of course you may need more HTML attributes for other purposes:
const dropDowns = Array.from(document.querySelectorAll(".option"));
function reset(i) {
for (let other of dropDowns.slice(i)) {
other.selectedIndex = 0;
other.disabled = other !== dropDowns[i];
}
}
document.addEventListener("change", function (e) {
let i = dropDowns.indexOf(e.target);
if (i < 0) return;
// only allow input in next one if current value is not default:
reset(i+(dropDowns[i].selectedIndex > 0));
});
reset(0); // on page load, disable all except first one
<select class="option">
<option>default option</option>
<option>1</option>
<option>2</option>
</select>
<select class="option">
<option>default option</option>
<option>A</option>
<option>B</option>
</select>
<select class="option">
<option>default option</option>
<option>x</option>
<option>y</option>
</select>
<select class="option">
<option>default option</option>
<option>alpha</option>
<option>beta</option>
</select>
More on the following:
reset(i+(dropDowns[i].selectedIndex > 0));
dropDowns[i].selectedIndex will be 0 when the first entry (default) is selected, and a strictly positive number when any other entry is selected. So with > 0 this actually gives true for when a non-default entry is selected, false otherwise.
Now we want to make the next dropdown available only when the current one has a non-default entry selected, i.e. when this > 0 expression is true. By involving that expression in a + operation, we convert that boolean value to a number (0 for false, 1 for true). And so, that whole expression is either i+0 or i+1, depending on whether the current dropdown has the default value selected or not.
By providing that index (i or i+1) to the reset function, we make sure that the effect of selecting the default value or not is just like is needed.
There are many ways to accomplish this. The below should work with any number of select boxes. The code is commented to explain the steps.
<form accept="#" method="POST" id="myform">
<div>
<select name="firstoption">
<option value="">default option</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div>
<select name="secondoption" disabled>
<option value="">default option</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<select name="thirdoption" disabled>
<option value="">default option</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>
<select name="fourthoption" disabled>
<option value="">default option</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
<script>
//get references to the DOM elements we need
var form = document.getElementById('myform');
var selects = form.querySelectorAll('select');
//register event listeners for each of the select boxes so we know when the value changes
for( let i=0; i<selects.length; i++ ) {
selects[i].addEventListener('change', function(evt) {
//select box "i" has changed
//since the value changed, reset other boxes after to the default value and disable
for( let i2 = (i+1); i2 < selects.length; i2++ ) {
selects[i2].value = "";
selects[i2].disabled = true;
}
//if the value of the changed select box is not the default, enable the next one
if( selects[i].value !== "" && selects[i+1] ) {
selects[i+1].disabled = false;
}
});
}
//catch form submission so we can validate the select boxes
form.addEventListener('submit', function(evt) {
//ensure we have all values before submitting
try {
for( let i=0; i<selects.length; i++ ) {
if( selects[i].value === "" ) {
alert(`Please select an option for box number ${i+1}`);
throw 0;
}
}
}catch(e) {
//error, prevent submission
evt.preventDefault();
return false;
}
//all good, submit
return true;
});
</script>
Load all select with document.querySelectorAll() using an expresion to get elements wich name ends with option, that's what $ do before the equal sign.
Then, in your function, check every select if one is empty, set to default value the next.
// Get all items wich name ends with "option"
let selects = document.querySelectorAll('[name$="option"]');
function refresh() {
// Loop into all selects
selects.forEach((item, index) => {
// Don't do this on last one
if(item.value == '' && index < selects.length - 2)
selects[index + 1].value = ""
});
// Check here the sixthoption value if you need it not empty to submit the form
}
<select name="firstoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="secondoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="thirdoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fourthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fifthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="sixthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Another way using if's:
// Get all items wich name ends with "option"
let selects = document.querySelectorAll('[name$="option"]');
function refresh() {
// 0 = firstoption, 1 = secondoption... 5 = sixthoption
// If value is empty string, set default value for next element too
if(selects[0].value == "") selects[1].value = '';
if(selects[1].value == "") selects[2].value = '';
if(selects[2].value == "") selects[3].value = '';
if(selects[3].value == "") selects[4].value = '';
if(selects[4].value == "") selects[5].value = '';
}
<select name="firstoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="secondoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="thirdoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fourthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fifthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="sixthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I assume that you not necessarily want to post upon each select change. Instead, let's see this approach:
<select class="fancy-select" id="s-1" name = "firstoption">
<option value = "">default option</option>
<option value = "1">1</option>
</select>
<select class="fancy-select" id="s-2" name = "secondoption">
<option value = "">default option</option>
<option value = "2">2</option>
</select>
<select class="fancy-select" id="s-3" name = "thirdoption">
<option value = "">default option</option>
<option value = "3">3</option>
</select>
<select class="fancy-select" id="s-4" name = "fourthoption">
<option value = "">default option</option>
<option value = "4">4</option>
</select>
<script type="text/javascript">
function myHandler() {
if (!this.value) {
var currentID = parseInt(this.id.substring(2));
for (let i = currentID; i < fancySelects.length; i++) fancySelects[i].value = "";
}
}
var fancySelects = document.querySelectorAll(".fancy-select");
for (let item of fancySelects) item.addEventListener("change", myHandler);
</script>
Fiddle: https://jsfiddle.net/0dfxytpc/1/
You see that despite the claims about Vue JS and jQuery making it easier, Javascript in itself is easy. If you know how to program in Javascript. My understanding is that once default is chosen you intend the subsequent items to be defaulted. If that's not the aim, then I misunderstood the goal.
Now, you can notice that this is pretty repetitive, we can surely make it nicer to appear. Let's generate the select tags on the server:
<?php
for ($index = 1; $index <= 4; $index++) {
?>
<select class="fancy-select" id="s-<?php echo $index; ?>">
<option value="">default option</option>
<option value="<?php echo $index; ?>"><?php echo $index; ?></option>
</select>
<?php
}
?>
<script type="text/javascript">
function myHandler() {
if (!this.value) {
var currentID = parseInt(this.id.substring(2));
for (let i = currentID; i < fancySelects.length; i++) fancySelects[i].value = "";
}
}
var fancySelects = document.querySelectorAll(".fancy-select");
for (let item of fancySelects) item.addEventListener("change", myHandler);
</script>
The code is small and easy to understand. Vue JS and jQuery would just overcomplicate this, they would add dependencies that you do not need. There is a trend of programmers who are less capable to work in Javascript and will argue that doing stuff is easier in Vue JS or jQuery. You can actually measure the power of that trend with the number of downvotes I get. I do not speak against the use of jQuery or Vue JS in general, although, I am not their fan in particular, but when you learn Javascript you should avoid getting dependant of a framework right from the start. As you get comfortable working with Javascript you might decide that Vue JS and jQuery is good for you. I would totally respect that decision, but do not make that decision before you learn Javascript properly.
You could try this:
const selects = document.querySelectorAll(".myoption");
const submit = document.getElementById("mysubmit");
selects.forEach((select, id) => select.addEventListener("change",() => {
const last = id === selects.length - 1;
if(! last) {
selects[id + 1].removeAttribute("disabled");
selects[id + 1].value = "";
}
for(let i = id + (select.selectedIndex ? 2 : 1); i < selects.length; ++i) {
selects[i].value = "";
selects[i].setAttribute("disabled", true);
}
submit.setAttribute("disabled", true);
if(last && select.selectedIndex) submit.removeAttribute("disabled");
}));
<select class="myoption">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" id="mysubmit" value="submit" disabled>
Hope this helps.
As already a lot of ways are mentioned, here is what I came up with.
Assign every select a data-name attribute.
Every select would also have a class attribute. This class attribute would possess all previous parents' data-names.
When a particular select value changes, you get the data-name of it and use querySelectorAll to get all those elements who have this data-name in their class and set their values and disability accordingly.
var selects = document.querySelectorAll('select');
selects.forEach(function(select_dropdown){
select_dropdown.addEventListener('change',function(){
var kids = document.querySelectorAll('.' + this.getAttribute('data-name'));
var parent_value = this.value;
kids.forEach(function(child,index){
child.value = "";
if(parent_value == "" || index > 0){
child.setAttribute('disabled','disabled');
}else{
child.removeAttribute('disabled');
}
});
});
});
<select class="" data-name="select_1">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_2" class="select_1" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_3" class="select_1 select_2" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_4" class="select_1 select_2 select_3" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_5" class="select_1 select_2 select_3 select_4" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_6" class="select_1 select_2 select_3 select_4 select_5" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
You can add data attribute for each dropdown, that way you can track index of that dropdown, so on change all higher than index apply action..
when option is selected, reset rest of the boxes that are in order.
If previus select box not default, enable next box else disable it
var selects = document.getElementsByClassName("select")
for(var i = 0; i < selects.length; i++){
selects[i].addEventListener('change', function(e){
for(var x = 0; x < selects.length; x++){
//On select, reset selectboxes that commes after
if(Number(e.target.dataset.columns) < x){
selects[x][0].selected = true;
}
//If previus select box not default, enable next box
if(x > 0 && selects[x -1][0].selected != true){
selects[x].disabled = false;
}
//else dissable next box..
else if(x > 0 && selects[x -1][0].selected == true){
selects[x].disabled= true;
}
}
})
}
<select data-columns="0" class="select">
<option value = "">default option</option>
<option value = "1">1</option>
<option value = "1">1</option>
</select>
<select data-columns="1" disabled class="select">
<option value = "">default option</option>
<option value = "2">2</option>
<option value = "1">1</option>
</select>
<select data-columns="2" disabled class="select">
<option value = "">default option</option>
<option value = "3">3</option>
<option value = "1">1</option>
</select>
<select data-columns="3" disabled class="select">
<option value = "">default option</option>
<option value = "4">4</option>
<option value = "1">1</option>
</select>

How to count the number of Form selects that have had values changes in Jquery/Javascript

I have several selects in my form. If one select has had its options changed then it should increase the counter. 5 selects then counter should be 5. Essentially I want to check if all my selects have been selected so I can submit the form. I don't want to use "required".
<div id="firstPanelID"
<div class="form-group input-group">
<label class="fixingLabelAlignmentInner">Transfer Code of Center from which Infant Transferred : </label>
<div class="fixingInputAlignmentInner">
<select id="transferCodePIW" name=transferCodePIW class="form-control" style="height:32px;width:80%;">
<option disabled selected value>SELECT</option>
<option value="13240">13240 - Mowbray Maternity Hospital</option>
<option value="14994">14994 - New Somerset Hospital</option>
<option value="16011">16011 - Tygerberg Hospital</option>
<option value="8005432">8005432 - Khayelitsha District Hospital</option>
<option value="8005433">8005433 - Michell's Plain District Hospital</option>
<option value="8005435">8005435 - Red Cross Children's Hospital</option>
<option value="97777777">97777777 - Birth at Home or in Transit</option>
<option value="">Other</option>
<option value="77777777">N/A</option>
<option value="99999999">Unknown</option>
</select>
</div>
</div>
</div>
I have tried it with the following. The selects may be visible/invisible due to other radio buttons hence the visible. The function works for radio buttons but I can't get it to work for selects.
var sgroups = [];
$('#firstPanelID select:visible:selected').each(function(index, el){
var i;
for(i = 0; i < sgroups.length; i++)
if(sgroups[i] == $(el).attr('name'))
return true;
sgroups.push($(el).attr('name'));
}
);
alert(($('#firstPanelID select:visible:selected').length))
I think the code is self-explanatory.
var counter = 0;
$('select').change(function () {
var o = $(this);
if (!o.hasClass('counted')) {
counter++;
o.addClass('counted');
}
$('#counter').text(counter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
<select>
<option value="2aa">2aa</option>
<option value="2bb">2bb</option>
<option value="2cc">2cc</option>
</select>
<select>
<option value="3aa">3aa</option>
<option value="3bb">3bb</option>
<option value="3cc">3cc</option>
</select>
<div id="counter">
0
</div>
If you want to check if all selects have been checked, assuming each select will have an empty value, you can do this:
function isThereAnyEmptySelection () {
let r = false;
$('select').each(function () {
if ($(this).val() === '') { // or === null, or === undefined, or === '0' etc., depending on context
r = true;
}
});
return r;
}
You can use .one() to attach a single change event to each <select> element, when count is equal to $("selector").length call .off() to remove change event, then perform action, for example, submit <form> element.
let count = 0;
$("select").one("change", function() {
++count;
console.log(count);
if (count === $("select").length) {
$("select").off("change");
// submit form here
console.log(count + " is " + $("select").length)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

JavaScript - Check multiple SELECT for duplicate options

This question is based on THIS QUESTION
When an option from one of the SELECT boxes were selected, I wanted the rest to be repopulated, without said option, but instead, is there an easy way to loop through all these select items, to ensure the same option hasn't been selected twice?
Thanks.
Person Number 1
<select name="person1">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 2
<select name="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 3
<select name="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Basic Overview:
JavaScript loop to ensure none of the options have been selected twice?
<!DOCTYPE html>
<html>
<head>
<script>
function doAction(el) {
for (var i = 0; i < document.getElementById('person2').length; i++) {
var v = (i != el.selectedIndex ? '' : 'disabled');
document.getElementById('person2')[i].disabled = v;
if (document.getElementById('person2').selectedIndex == el.selectedIndex)
document.getElementById('person2').selectedIndex = 0;
document.getElementById('person3')[i].disabled = v;
if (document.getElementById('person3').selectedIndex == el.selectedIndex)
document.getElementById('person3').selectedIndex = 0;
}
}
</script>
</head>
<body>
Person Number 1
<select id="person1" onchange="doAction(this)" >
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
If you use
var x = document.getElementByName('person1').value;
var y = document.getElementByName('person2').value;
var z = document.getElementByName('person3').value;
you can get the values. Then, you have 3 items, to compare against all of them you just have to do 3 checks:
if(x == y || x == z || y == z){
...
}
Or you could throw all of the values into an array, and then splice out the first occurrence, and then check to see if it occurs again.
//get all selects
var selects = document.getElementsByTagName('select');
var setOfPeople = [];
for(i in selects){
setOfPeople[i] = selects[i].name;
}
var selections = [];
//put everything in an array
for(i in setOfPeople){
selections[i] = document.getElementByName(setOfPeople[i]).value;
}
for(i in setOfPeople){
var val = document.getElementByName(setOfPeople[i]).value;
//make sure the element is in the selection array
if(selections.indexOf(val) != -1){
//rip out first occurrence
selections.splice(selections.indexOf(val), 1);
}
//check for another occurrence
if(selections.indexOf(val) != -1){
...
}
}

Multiple identical <select> tags where each option can be selected once

I am creating a website where their are 4 identical dropdown menu's, each dropdown menu has got 10 options. But each of those options can only be selected in one of the dropdown menu's.
So for example:
When I select option 1 in this dropdown menu.
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I can't select it in this one. So it should say disabled in option one.
<select name="select2">
<option value="1" //disabled >1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I don't know how to do it myself so I would be very glad if someone could help me.
To provide a better user experience, you should disable the items using JavaScript when the user selects something in a drop down. Are you using jQuery by any chance?
You should also enforce it on the server because as a general rule, clients are not to be trusted.
If I understand you correctly, what you are trying to achieve is better done via checkboxes.
Instead of <select> do this:
<input type="checkbox" name="1" value="1">option1<br>
<input type="checkbox" name="2" value="2">option2 <br> ...
The code below does what you are asking. I also made a jsfiddle
It will correctly disable and enable options as options from ANY of the select inputs are changed.
The javascript
<script type="text/javascript">
// *** EDIT THIS ***
var selectIds = new Array('select1', 'select2', 'select3', 'select4'); // all of the select input id values to apply the only one option value anywhere rule against
function process_selection(theObj){
var allSelectedValues = new Array(); // used to store all currently selected values
// == get all of the currently selected values for all the select inputs
for (var x=0; x<selectIds.length; x++){
var v = document.getElementById(selectIds[x]).value; // the value of the selected option for the select input currently being looked at in the loop (selectIds[x])
// if the selected option value is not an empty string ..
if(v!==""){
// store the value of the selected option and it's associated select input id value
allSelectedValues[v] = selectIds[x];
}
}
// == now work on each option within each select input
for (var x=0; x<selectIds.length; x++){
// loop thru all the options of this select input
var optionObj = document.getElementById(selectIds[x]).getElementsByTagName("option");
for (var i = 0; i < optionObj.length; i++) {
var v = optionObj[i].value; // the value of the current option in the iteration
// only worry about option values that are not an empty string ("")
if(v!==""){
if(allSelectedValues[v]){
if(allSelectedValues[v] && allSelectedValues[v] != selectIds[x]){
// disable this option because it is already selected
// and this select input is NOT the one that it is selected in
optionObj[i].disabled = true;
}
}else{
// enable this option because it is not already selected
// in any of the other select inputs
optionObj[i].disabled = false;
}
}
} // end for (option loop)
} // end for (select loop)
} // end func
</script>
The HTML that works with the above
But really the code above will work with any select inputs on your page by editing the one line indicated in the js code above
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select3" id="select3" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select4" id="select4" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
As others have mentioned, it is a cleaner way to do it in checkboxes. However, just to improve my JavaScript skills, I came up with something that should answer what you asked for:
var boxes, i, disableOthers;
boxes = document.getElementsByTagName('select');
disableOthers = function () {
'use strict';
var i, j, k, selectedValues = [],
options;
for (i = 0; i < boxes.length; i += 1) {
selectedValues.push(boxes[i].value);
for (j = 0; j < boxes.length; j += 1) {
if (boxes[j] !== boxes[i]) {
options = boxes[j].querySelectorAll('option');
for (k = 0; k < options.length; k += 1) {
options[k].disabled = (selectedValues.indexOf(options[k].value) > -1);
}
}
}
}
};
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', disableOthers, false);
}
See jsFiddle

Categories

Resources