I want to disabled option on select without click any button. How can I do that? I tried this. use id on option in JS
html code:
<select name="select01" id="select01" onchange="handleSelect()"> <option value="01" id="01">01</option> <option value="02" id="02">02</option> <option value="03" id="03">03</option> </select>
JS code:
<script> function handleSelect() { if (this.value == '02') { document.getElementById('02').disabled=true; } } </script>
From what I know from the code JS, option with id 02 will be disabled but it it does not work. I have tried search inside stack over flow but do not find one.
Advertisement
Answer
In your eventhandler you need to pass in the element onchange="handleSelect(this)"
. Then use it:
function handleSelect(ele) { if (ele.value == '02') { document.getElementById('02').disabled=true; } }
Also note that id
isn’t supposed to be strictly numerical, while it’s supported in HTML 5 it isn’t below HTML 4.01 where it needs to start with a letter.
Also if you attach the event handler purely in JavaScript you can just do:
document.getElementById("select01").onchange = function() { if (this.value == '02') { document.getElementById('02').disabled=true; } }