Home > other >  How do I disable a dropdown menu based on another dropdown menu value
How do I disable a dropdown menu based on another dropdown menu value

Time:11-22

Below is my html code, and script, to select multiple option from a drop-down menu.

I wanted to give the user an additional option when selecting a specific value in one drop-down list which would allow the user to provide additional input.

The script below does not seem to disable the second drop-down menu when "Plant Machine" is selected in the first drop-down menu:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.jquery.min.js"></script>
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet" />
<div class="control-group ">

  <label for="company" class="sr-only">machine</label>
  <div class="controls">
    <select name="company" class="form-control" id="company" required>
      <option></option>
      <option value="Hire">Plant Hire</option>
      <option value="Machine">Plant Machine</option>
      <option value="Store">Plant Store</option>
      <option></option>
    </select>
  </div>
</div>

<div class="control-group">
  <div class="controls">
    <label for="machine" class="sr-only">Machinery</label>
    <select name="machine" id="machine" data-placeholder="Select 1 or Multiple Machinery" multiple class="chosen-select">
      <option></option>
      <option>TLB 4x4 with a bucket</option>
      <option>Tipper truck 10m^3</option>
      <option>Grader</option>
      <option>Roller (10ton)</option>
      <option>Excavator 30ton with a bucket </option>
      <option>Excavator 30ton with a pecker</option>
      <option>3.5ton pecker for excavator</option>
      <option>TLB 4x4 with a pecker</option>
      <option></option>
    </select>
  </div>
</div>

<script>
  document.getElementById('company').onchange = function() {
  
    if (this.value == "Machine") {
      document.getElementById('machine').removeAttribute('disabled');
    } else {
      document.getElementById('machine').setAttribute('disabled', true);
    }
    
  }
</script>

<script>
  $(".chosen-select").chosen({
    no_results_text: "Nothing Selected"
  })
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Because you have a style, that uses other elements as the presented select. The select itself has a display: none style and it actually gets disabled. Use something like pointer-events: none; on the div with id="machine_chosen". You can look for other options too how to disable it.

Also plus the above alternatively use

document.getElementById('machine').disabled = 'false';

CodePudding user response:

Change the code in else condition as below:

document.getElementById('machine').disabled=true;
  • Related