Peter
Peter

Reputation: 1919

Selectbox disabled or enabled by an option of an other selectbox

I try to create a relation/connexion beetwen 2 selectbox

<form id="creation" name="creation">
<select name="select01" id="select01">
     <option value="01">01</option>
     <option value="02">02</option>
     <option value="03">03</option>
</select>

<select name="select02" id="select02">
     <option value="aa">aa</option>
     <option value="bb">bb</option>
     <option value="cc">cc</option>
</select>
</form>

I want that my selectbox select02 be disabled at the begening, and when i click on value02 or value03, we enable it, and when we click on value01, disable it.

There is my code js for the moment. I try to adapt it from an other function (radiobutton enabling a selectbox) but it doesn't seem to work. My list is disable at the beging, but the onclick is not working ...

Some body can help me?

var oui = document.creation.select01[0];

document.getElementById("select02").disabled=true;
oui.onclick = function() {
document.getElementById("select02").disabled=false;
}

Ok, so NOW, i'm with this code:

<script>
var oui = document.select01;
document.getElementById("select02" ).disabled=true;
oui.onchange = function(){
document.getElementById("select02" ).disabled=false;
}
</script>

I change the value of my selec01, then my select02 is now enable .. but how can I target only 2 options of my select01 ?

Upvotes: 13

Views: 62979

Answers (4)

Peter
Peter

Reputation: 1919

function handleSelect() {
  if (this.value == '01') {
     document.getElementById('select02').disabled = true;
  } else {
     document.getElementById('select02').disabled = false;
  }
}

Upvotes: 0

cassi.lup
cassi.lup

Reputation: 1261

Try this:

<form id="creation" name="creation" onchange="handleSelect()">
<select name="select01" id="select01">
     <option value="01">01</option>
     <option value="02">02</option>
     <option value="03">03</option>
</select>

<select name="select02" id="select02" disabled>
     <option value="aa">aa</option>
     <option value="bb">bb</option>
     <option value="cc">cc</option>
</select>
</form>

And as a JS script:

 function handleSelect() {
     if (this.value == '01') {
         document.getElementById('select02').disabled = true;
     } else {
         document.getElementById('select02').disabled = false;
     }
 }

And a tip: explore jQuery, a very popular JS framework (jquery.com). You can achieve your task very simply by using it.

Upvotes: 14

Joseph Silber
Joseph Silber

Reputation: 219938

​document.getElementById('select01').onchange = function () {
    document.getElementById("select02").disabled = this.value == '01';
}​​​​​​​​

Here's the fiddle: http://jsfiddle.net/PK2vc/

Upvotes: 3

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

You must use onchange instead of onclick. So below should be

oui.onclick = function() 

Replaced with

oui.onchange = function() 

Good Luck !!

Upvotes: 1

Related Questions