ethem
ethem

Reputation: 2918

checkbox checked in JQuery is not working

I've a simple situation. When the checkbox is checked then the textbox is shown. Unchecking checkbox will hide the textbox.

I move the value to (asp:Textbox) textboxA.text and set the (asp:Checkbox) "chkboxA" to Checked in Server side (Page load).

then my jquery code document.ready is executed.

C# code behind

 protected override void OnLoad()
    {   textboxA.Text = "Hello World";
        chkboxA.Checked = !string.IsNullOrEmpty(textboxA.Text);
    }

JQUERY CODE:

$('input[id$=chkboxA]').click(function () {
    var checked_status = this.checked;
    if (checked_status == true) {
        $('input[id$=textboxA]').show();
    }
    else {
        $('input[id$=textboxA]').hide();
    }
});

$('input[id$=chkboxA]').click();  //this statment triggers the checkbox checked

PROBLEM: When the page is first shown the "textboxA" is shown but the checkboxA is unchecked. Then when I click on the checkboxA the checkbox is checked and the TextboxA remains on the screen. Then when I click on the CheckboxA again to uncheck then the texboxA is not shown.

so the issue is on first load (first shown on the screen).

Why is the checkboxA not checked when the page is first shown while the TextboxA is shown?

what is wrong in my code?

Upvotes: 0

Views: 3640

Answers (3)

Al-Mothafar
Al-Mothafar

Reputation: 8219

Try add this line :

if ($('input[id$=chkboxA]').is(':checked')) {
    $('input[id$=textboxA]').show();
}
else {
    $('input[id$=textboxA]').hide();
}

after :

$('input[id$=chkboxA]').click();

If you remove : $('input[id$=chkboxA]').click(); you will see that textbox will hidden.

Upvotes: 0

huMpty duMpty
huMpty duMpty

Reputation: 14470

I think easiest way is to use toggle()

try something like this

Initially set the visible false in textbox

    $(".chk").click(function() {
    $(".txt").toggle(this.checked);
    });

Something like http://jsfiddle.net/5udtC/1880/

Upvotes: 2

John Gathogo
John Gathogo

Reputation: 4655

Here is how I would go about it: Instead of,

chkboxA.Checked = !string.IsNullOrEmpty(textboxA.Text);  

you could have a script that is executed once the page is done loading (in you markup)

<script type="text/javascript">
    $(document).ready(function() {
        if($('#textboxA').attr('value') != '') {
            $('#chkboxA').attr("checked", "checked");
        } else {
            $('#chkboxA').attr("checked", false);
        }
    });
</script>

Then, when evaluating whether the checkbox is checked, you could use:

$('#chkboxA').click(function () {

    if (this.attr('checked')) {
        $('#textboxA').show();
    }
    else {
        $('#textboxA').hide();
    }
});

Upvotes: 0

Related Questions