Reputation: 31
I have about 10 select boxes added to a form using a loop. All with the same number of options.
<?php
for($i=1; $i<11; $i++){
?>
<select name="doc[]"; id="doc<?php echo $i?>"; autocomplete="off";
onchange='disable()' required>
<option value="none" disabled selected>Select</option>
<option value=0>A</option>
<option value=1>B</option>
<option value=2>C</option>
<option value=3>D</option>
<option value=4>E</option>
<option value=5>F</option>
<option value=6>G</option>
<option value=7>H</option>
<option value=8>I</option>
</select>
<?php
}
?>
I want if I select first option in first select box, the next select box should not have that option. In pure Javascript, not Jquery.
I have tried writing something like:
function disable(){
for(var i=1; i<9; i++){
var val = document.getElementById('doc'+i).value;
document.getElementById("doc"+(i+1)).options[val].disabled =
true;
}
}
But it is not working as I expected.
Upvotes: 0
Views: 406
Reputation: 31
After so many hours of trying as a novice, I have managed to fix this by modifying and re-modifying the JS code and finally ending with the following: There were 10 select menus, so I have changed the loop variable total to <11
function disable(){
for(var i=1; i<11; i++){
var doc = document.getElementById('doc'+i);
var changesource=event.target.id || event.srcElement.id;
if(changesource==doc.id){
var val = doc.selectedIndex;
for(var m=i+1; m<11; m++){
document.getElementById('doc'+m).options[val].remove();
}
}
else{
continue;
}
}
}
Upvotes: 1
Reputation: 159
Ok, this has to be done in some steps.
Getting the value of the selected option:
var select = document.getElementById("doc1");
var value = select.value;
Fire a change event when you select an option:
let doc = document.querySelector('#doc1');
doc.addEventListener('change', function() {
document.getElementById("doc2").options[value ] = null;
})
You use this to your own liking, using array map or loop to set up the serial of select boxes in any way you want. A word of advice, you probably should try around with javascript a bit more before attempting more advanced codes since I see no indication that you tried a solution at all. It is ok to be a novice, we all were there one time. But I really suggest you take a look at this and try it your own way. It is not exactly a duplicate since it deals with only two dropdowns, but it is a start and will give you a basic idea of what you are doing. (How do I remove options from a dropdownlist in javascript?)
Upvotes: 0