lundi 29 novembre 2021

Javascript hide/show elements does not work properly

I have added this checkbox to my form:

<div class="row">
  <div class="form-group col">
    <input type="checkbox" name="prd_presell" id="product_presell" 
      onclick="presellTXT()" value="TRUE" @if(!empty($product)) @if($product->prd_presell == 'TRUE') checked @endif @endif>
    <label for="presell_product">Presell Product</label>
  </div>
</div>

So there is an onClick function named presellTXT() which goes like this:

function presellTXT() {
        var presell_checkbox = document.getElementById("product_presell"); // get checkbox
        
        var presell_text = document.getElementById("show_presell_text"); // text div
        
        var presell_text_input = document.getElementById("presell_product_text"); // text input
        
        if (presell_checkbox.checked == true){
            presell_text.style.display = "block";
        } else {
            presell_text_input.value = "";
            presell_checkbox.value = "";
            presell_text.style.display = "none";
        }
    }

So when the checkbox is checked, it basically shows the element with an id of show_presell_text:

<div class="row" id="show_presell_text">
  <div class="col-lg-12">
    <div class="form-group">
      <label>Product Presell Text:</label>
      <input name="prd_presell_text" id="presell_product_text" class="form-control" value="">
    </div>
  </div>
</div>

So when the page loads, it should not be showing the Product Presell Text unless the checkbox is checked.

Now if you take a look at jsfillde example, you can see as soon as the page loads, the text input appears however the checkbox is not checked at all!

So how to hide the text input when the page loads and the checkbox is not checked?

Note: I don't want to use CSS for this because I need to determine correctly if prd_presell is checked on page loads (because of @if($product->prd_presell == 'TRUE') which retrieves data from the DB) then it has to show the Product Presell Text text input.




Aucun commentaire:

Enregistrer un commentaire