Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript show/hide not working as expected with html field

The following is the chose I am using to let the user manually choose working/starting time.

<input type="checkbox" class="testmethod" id="beastmode" name="beastmode" tabindex="5">Beast Mode</input>

<div class="input-group date" id="id_1">
      <input type="text" name="day11" value="09:00 AM" class="form-control"
          placeholder="End time" title="" required/>
        <div class="input-group-addon input-group-append">
              <div class="input-group-text">
                   <i class="glyphicon glyphicon-time fa fa-clock-o"></i>
              </div>
        </div>
    </div> 


    <script>
  $("#beastmode").click(function () {
    if ($(this).prop('checked') === true) {
        $('#id_1,#id_2').show();
    } else {
        $('#id_1,#id_2').hide();
    }
});
</script>

By default the field should be hidden, but it is not. Instead even in the checkbox is not checked, the field is visible and to make it hidden I had to check the box and uncheck it again. Then the input field goes hidden. How can i fix this ?

Here is the jsfiddle link, it shows the same problem.
https://jsfiddle.net/shijilt/bs02m98w/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code is only changing the visibility after clicking the #beastmode element. There’s no explicit default otherwise.

You can hide it when the page loads:

$(function () {
  $('#id_1,#id_2').hide();
});

Or, even better, style it to be hidden by default in your CSS:

#id_1,#id_2 {
  display: none;
}

That way it’s hidden by default from the styling itself, regardless of whether or not any JavaScript code successfully executes.

Example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading