NickiJey
NickiJey

Reputation: 27

disable select if checkbox is checked

I have a html/php script where there is a Select I want to be "disabled" if checkbox is not checked.

This is the script:

<input type="checkbox" name="stOne" id="stOne" value="1"/>

<select class="input" name="selectOne" id="selectOne">
    <?php
        $check_sql = mysql_query("SELECT * FROM DBtable");
        while ($check_row = mysql_fetch_assoc($check_sql))
        {
            $id = $check_row['id'];
            $st = $check_row['style'];

            echo "<option value='" . $st . "'>" . $st . "</option>";
        }
    ?>
</select>

I found many scripts here on stack overflow with a solution that didn't work in my code.

Can someone help me with this?

Is it possible to do this NOT with jQuery?

Upvotes: 2

Views: 7740

Answers (3)

D Coder
D Coder

Reputation: 572

try this

      <input type="checkbox" name="stOne" id="stOne" value="1" onClick="disableChecked()"/>
  <select class="input" name="selectOne" id="selectOne">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
  </select>

  <script>
   window.onload = disableChecked(); 

   function disableChecked()
   {
     if($("#stOne").is(':checked')){
       $("#stOne").attr("disabled", true);
     }
    }

   </script>

Upvotes: 0

Vipin CP
Vipin CP

Reputation: 3797

You can do this using jquery as mentioned below -

<input type="checkbox" name="stOne" id="stOne" value="1"/>
<select class="input" name="selectOne" id="selectOne">
    <?php
        $check_sql = mysql_query("SELECT * FROM DBtable");
                while ($check_row = mysql_fetch_assoc($check_sql))
                {
                $id = $check_row['id'];
                $st = $check_row['style'];

                echo "<option value='" . $st . "'>" . $st . "</option>";
                }
    ?>
</select>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 <script>
$( "#stOne" ).change(function() {
if ($('#stOne').prop('checked')) {
     $(".input").prop("disabled", true);
}
else
{
     $(".input").prop("disabled", false);
}

});

</script>

Upvotes: 0

ADreNaLiNe-DJ
ADreNaLiNe-DJ

Reputation: 4919

Here is what you need in native JS:

window.onload = toggleSelect(); // to disable select on load if needed

function toggleSelect()
{
  var isChecked = document.getElementById("stOne").checked;
  document.getElementById("selectOne").disabled = !isChecked;
}
<input type="checkbox" name="stOne" id="stOne" value="1" onClick="toggleSelect()"/>
<select class="input" name="selectOne" id="selectOne">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Upvotes: 6

Related Questions