lundi 15 juin 2020

Handle checkbox with jQuery

I have two checkboxes, onchange/onclick of a checkbox the respective input tag should show/hide. My sample code forces both the checkbox to be in already selected state. However, when I unselect one of the CB nothing happens.

Goal: On select of CB1 input1=show() input2=hide() On select of CB2 input1=hide() input2=show() Both selected input1=show() input2=show()

index.html

<div class="clr-control-container">
    <div class="clr-checkbox-wrapper">
        <input type="checkbox" id="vertical-checkbox1" class="clr-checkbox" >
        <label for="vertical-checkbox1" class="clr-control-label">CB 1</label>
    </div>
    <div class="clr-checkbox-wrapper">
        <input type="checkbox" id="vertical-checkbox2" class="clr-checkbox" >
        <label for="vertical-checkbox2" class="clr-control-label">CB 2</label>
    </div>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
    $("#input1").hide();
    $("#input2").hide();
    if($("#vertical-checkbox1").attr("checked", true) && $("#vertical-checkbox2").attr("checked", true))  {
        $("#input1").show();
        $("#input2").show();
    } 
    else if($("#vertical-checkbox1").attr("checked", true) && $("#vertical-checkbox2").attr("checked", false)){
        $("#input1").show();
        $("#input2").hide();
    }
    else if($("#vertical-checkbox1").attr("checked", false) && $("#vertical-checkbox2").attr("checked", true)){
        $("#input1").show();
        $("#input2").hide();
    }
    else{
        $("#input1").hide();
        $("#input2").hide();
    }
});
</script>



Aucun commentaire:

Enregistrer un commentaire