Display Checks on Checkboxes if other input is made

Viewed 30

I am trying to show a checked checkbox if a value is selected on a select input. So if someone is choosing any value in the dropdown I want the checkbox to switch from off to on. Here is the html example.

I tried different things to achieve that but it is not working at all. My latest try looks like this:

$(document).ready(function() {
  $('#subject').each(function() {
    if (this.selected)
      $("#box-4").prop("checked", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select type="number" id="subject" name="subject">
  <option value="none" selected disabled hidden>none</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

<input type="checkbox" id="box" disabled="disabled">

I think that I am on the right track here but don´t understand why this isn´t working at all.

2 Answers
  1. It should be .change()

  2. Don't check whether it is selected or not

$(document).ready(function() {
  // Change event
  $('#subject').change(function() {
    // On change, at first reseting all checkboxes state
    $('input[type="checkbox"]').each(function() {
      $(this).prop('checked', false);
    });
    // After reseting checkboxes state, check the appropriate checkbox
    $("#box-" + this.value).prop("checked", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select type="number" id="subject" name="subject">
  <option value="none" selected disabled hidden>none</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

<input type="checkbox" id="box-1" disabled>
<input type="checkbox" id="box-2" disabled>

$(document).ready(function() {
  $('#subject').click(function() {
    var option = document.getElementById('subject');
    console.log(option.value);
    if (option.value ==1 ||option.value==2)
      $("#box").prop("checked", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select type="number" id="subject" name="subject">
  <option value="none" selected disabled hidden>none</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

<input type="checkbox" id="box" >

Related