Home > Software engineering >  Disable HTML Select Using JavaScript
Disable HTML Select Using JavaScript

Time:10-19

I have this list

<select name="method" required class="form-control">
    <option value="1">Cash</option>
    <option value="2">Credit</option>
</select>

<select name="method2" class="form-control">
<?php
while (...) {
echo '<option value="id">Title</option>';
}

?>
</select>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If the user chooses the Cash option from the first "select method",

the second "select method2" must be disabled, and if he chooses Credit, it must be activated

How do I do that?

Thanks in advance

CodePudding user response:

In it's simplest form, you can add an event listener to your first select box that listens for a change event:

let selectOne = document.querySelector("#select-1"), selectTwo = document.querySelector("#select-2");

selectOne.addEventListener("change", () => {
  if (selectOne.value == 1) {
    selectTwo.disabled = true;
  } else {
    selectTwo.disabled = false;
  }
})
<select name="method" required class="form-control" id="select-1">
    <option value="-">-</option>
    <option value="1">Cash</option>
    <option value="2">Credit</option>
</select>

<select name="method2" class="form-control" id="select-2">
  <option value="-">-</option>
  <option value="1">Just For Demo Purposes</option>
</select>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

First you can listen for any changes in the select using change event

The select element in HTML has a disabled property, which is set to false by default unless its explicitly disabled, you can set this property to True or False to enable or disable the select respectively

const sel = document.getElementById('selectm');
const sel2 = document.getElementById('selectm2');

handler = () => {
    console.log(sel.value)
    if (sel.value == 1) sel2.disabled = true
    else sel2.disabled = false;
}
sel.addEventListener('change', handler)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <select name="method" required class="form-control" id="selectm">
        <option value="0">Default</option>
        <option value="1">Cash</option>
        <option value="2">Credit</option>
    </select>
    
    <select name="method2" class="form-control" id="selectm2">
        <option value="1">test</option>
        <option value="2">test-1</option>

    </select>
</body>
</html>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related