1

I have a dropdown select box with "Select one" as a default option and the View report submit button

<select name="time" id="time" required>
 <option value="0" selected>Select one</option>
 <option value="1">Value 1</option>
 <option value="2">Value 2</option>
</select>
<input type="submit" name="act" value="View Report" disabled>

The submit button is disabled until either value 1 or 2 is chosen. How can I do this without using jquery? Thank you.

treepl
  • 35
  • 7
  • Can you explain what you tried? – Fusei May 27 '21 at 10:08
  • @Fusei i tried the if else statement if (time.options.value != "0") then document.getElementbyID("btn").disabled = true. I was setting id="btn" for the submit button – treepl May 27 '21 at 10:12
  • i also tried if (time.options.length == 0) with the same statement but realized "select one" is a select option already :P – treepl May 27 '21 at 10:14
  • 1
    Sorry. Then you should use addEventListner. Anyway, my code works fine. Thank you for your cooperation! – pullidea-dev May 27 '21 at 11:02

2 Answers2

3

As you can see i add an addEventListener to select, so when that change the script will check if value is different to 0

const select = document.getElementById('time');
const submitButton = document.getElementById('submit');
document.getElementById('time').addEventListener('change', () => {
  if (select.value === '0') {
    submitButton.disabled = true;
  } else {
    submitButton.disabled = false;
  }
});
<select name="time" id="time" required>
  <option value="0" selected>Select one</option>
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
</select>
<input type="submit" name="act" id='submit' value="View Report" disabled>
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

You can use .prop() method. Good Luck!

<html>
  <head>
    <title>
    Bottom Nav Bar
    </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <body>
    <select name="time" id="time" required>
     <option value="0" selected>Select one</option>
     <option value="1" >Value 1</option>
     <option value="2">Value 2</option>
    </select>
    <input type="submit" name="act" value="View Report" disabled>
    </body>
     <script>
    $("#time").click(function() {
             if($("select").val() == 0)
           $("input").prop( "disabled", true);
            else $("input").prop( "disabled", false);
        });
    </script>
    </html>
pullidea-dev
  • 1,768
  • 1
  • 7
  • 23