1

I have a small script,with very straight function. If the checkbox is not checked, if the user clicked on it show a div otherwise hide the div when user clicks in it. The script is (its inside a PHP code ):

echo 
'<script> 
$(document).ready(function(){

if($("#chk_id'.$bank_name.'").is(":checked"))
{


   $("#chk_id'.$bank_name.'").click(function(){
      $("#form_show'.$bank_name.'").hide(300);
   });

}
else
{ 

    $("#chk_id'.$bank_name.'").click(function(){

    //alert("ddd");

    $("#form_show'.$bank_name.'").show(300);
   });
}
});    


</script>';

But the problem is although the show div is working, I am unable to hide the div ! Whats wrong? javascript library : <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

2
  • 1
    Show us your example in JSFiddle Commented Jul 31, 2013 at 12:14
  • And if you could add your html code too Commented Jul 31, 2013 at 12:16

4 Answers 4

3

Try this:

$(document).ready(function(){
    $('body').on('click', "#chk_id'.$bank_name.'", function() {
        if($("#chk_id'.$bank_name.'").is(":checked")) {
            $("#form_show'.$bank_name.'").hide(300);
        } else {
            $("#form_show'.$bank_name.'").show(300);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

3

I think your function should be something like this:

function checkBankName(){
    if($("#chk_id'.$bank_name.'").is(":checked"))
    {
        $("#form_show'.$bank_name.'").show(300);
    }
    else
    {
        $("#form_show'.$bank_name.'").hide(300);
    }
}

$(document).ready(function(){
    // first time
    checkBankName();

    // on check
    $("#chk_id'.$bank_name.'").click(function(){
        checkBankName();
    });
});   

Comments

0

try this:

Demo

 $("#chk_id").click(function(){
       if($('#chk_id:checked').length > 0){
          $('.bank_name').hide(300);
       }
       else{
          $('.bank_name').show(300);
       }
   });

I have guessed your html implementation. You may not need to include the #form_show in your selector.

Or, you could do something like this using toggle:

tioggle demo

// code to initialize state before click

$("#chk_id").click(function(){    
    $('.bank_name').toggle(300);            
});

Hope this helps

Comments

0

Simplified version of another answer here:

$(document).ready(function() {
    $("#chk_id' . $bank_name . '").change(function() {
        $("#form_show' . $bank_name . '")[this.checked ? 'show' : 'hide'](300);
    }).change();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.