theNuclear
theNuclear

Reputation: 15

Show on 'checked'

What's wrong with this example:

$('label#formSecondPhone:first-child').change(function() {
    var id = $('#formSecondPhoneField');
    $(this).attr('checked') ? $(id).show() : $(id).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label id="formSecondPhone"><input type="checkbox" name="secondContact" value="1"> Phone</label> 
<label id="formSecondPhoneField" class="form-item">Enter your number: <input type="number" name="secondPhone"></label>

The formSecondPhoneField is not showing / hiding

Upvotes: 2

Views: 30

Answers (1)

guradio
guradio

Reputation: 15555

  1. Change you selector of checkbox
  2. Use .is(":checked") to check for check status of checkbox

$(':checkbox[name=secondContact]').change(function() {
  var id = $('#formSecondPhoneField');
  
  console.log($(this).is(':checked'))
  $(this).is(':checked') ? $(id).show() : $(id).hide();
}).change();
#formSecondPhoneField {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="formSecondPhone"><input type="checkbox" name="secondContact" value="1"> Phone</label>
<label id="formSecondPhoneField" class="form-item">Enter your number: <input type="number" name="secondPhone"></label>

Upvotes: 2

Related Questions