UltraJ
UltraJ

Reputation: 487

How to Make Checkbox Visible Based on Selected Dropdown Item

I'm trying to get a checkbox and its related label (in the "addfiles" span) to appear only when drop down item 3 (attach files) is selected. The addfiles span will be hidden when its not selected.

I'm new to jQuery and I don't know where to begin to do this.

Thanks.

<!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

   <script>

  </script>
  </head>

  <body>
    <form name="frmChkForm" id="frmChkForm">
      <select name="service" id="service" class="required contact-service">
        <option value="">Select Option</option>
        <option value="1">feedback</option>
        <option value="2">updates</option>
        <option value="3">attach files</option>
      </select>

      <p>
        <span id="addfiles">
          <input type="checkbox" name="attachfiles" id="attachfiles" value="yes">Attach files    
        </span>
      </p>
    </form>
  </body>
</html>

Upvotes: 0

Views: 239

Answers (2)

rahul
rahul

Reputation: 187020

You can use .change() for the dropdown selection change.

this.value inside the .change() event should get the current selected value.

strict equal to operator can be used for the value comparison

.show() will show your hidden element

$(function()
{
    $("#service").change(function(){
        if(this.value === 3) {
            $("#addfiles").show();
        } else {
            $("#addfiles").hide();
        }
    });
});

You can have a detailed read in Selectors

Upvotes: 1

Franco
Franco

Reputation: 2329

You can do this:

 $(document).ready(function(){
       $('#addfiles').hide()
       $('#frmChkForm').change(function(){
          var selectedOption = $(this).val()
          if(selectedOption == 3){
              $('#addfiles').fadeIn()
          }else{
             $('#addfiles').fadeOut()
          }
       })
    })

Upvotes: 0

Related Questions