Home > Enterprise >  How ca i make a <select> with options that enable/disable a button
How ca i make a <select> with options that enable/disable a button

Time:06-02

i'm trying to do a multiple choice question that when selected the right answer enable a button

function enAble() {
  let possibleAns = document.getElementById('question').value;

  if (possibleAns != 1) {
    document.getElementById("btton").disabled = true;
  } else if (possibleAns = 1) {
    document.getElementById("btton").disabled = false;
  }
}
<select id="question" onchange="enAble()">
  <option>wrong answer</option>
  <option value="1">right answer</option>
  <option>wrong answer</option>
</select>

<button id="btton" type="button" disabled>button</button>

CodePudding user response:

Change possibleAns !=1 to possibleAns !==1

Also use possibleAns ===1 in else statement

CodePudding user response:

In else if (possibleAns = 1) {, (possibleAns = 1) is an assignment statement. Use else if (possibleAns == 1) { to check for equality.

CodePudding user response:

A cleanest way to code that (Imho).

const 
  select_element = document.getElementById('question')
, button_element = document.getElementById("btton")
  ;
select_element.onchange = () =>
  {
  button_element.disabled = (select_element.value != '1')
  }
<select id="question">
  <option value="0">wrong answer</option>
  <option value="1">right answer</option>
  <option value="2">wrong answer</option>
</select>

<button id="btton" type="button" disabled>
  button
</button>

  • Related