Home > Software design >  javascript show/hide not working as expected with html field
javascript show/hide not working as expected with html field

Time:08-03

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

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

<div  id="id_1">
      <input type="text" name="day11" value="09:00 AM" 
          placeholder="End time" title="" required/>
        <div >
              <div >
                   <i ></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/

CodePudding user response:

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

  • Related