0

I have this code in html I want to change the checkbox check and uncheck event using javascript on some event so I am calling function ChangeCheckBox() on button click

<div>
    <label class="checkbox line">
        <input type="checkbox" id="Add" />Add</label>
</div>
<script>
    function ChangeCheckBox() {
        var AddCheck = 0;
        if (AddCheck == 1) {
            document.getElementById("Add").checked = true;
        } else {
            document.getElementById("Add").checked = false;
        }
    }
</script>

So in above condition check box should unchecked but its not happening checkbox is remaining checked after running this code

3
  • the if block is redundant. The if wont execute ever as you are setting AddCheck = 0 always in this function.It will always land in the else block Commented Sep 2, 2015 at 8:03
  • means can you be more specific please Commented Sep 2, 2015 at 8:04
  • Its just a piece if code i posted is to understand actual code AddCheck is dynamic and it sets according to some conditions Commented Sep 2, 2015 at 8:07

2 Answers 2

3

Since you are setting AddCheck = 0;, of course it will not keep it's state, because you are reseting the value. If you want to simulate a toggle, here's a simpler alternative.

<script>
    function ChangeCheckBox() {
        var el = document.getElementById("Add");
        el.checked = !el.checked;
    }
</script>
Sign up to request clarification or add additional context in comments.

9 Comments

Ok there is not problem with my if box the values are ruuning perfectly this is a sample code to understand my problem. Actual code differs. My problem is just i cannot programitically check uncheck the check boxes.
@Snehal I am not sure what the actual problem is then. It sounds like a logic error. Here's a fiddle jsfiddle.net/vsxa8gf3 to help you out.
Dude its 100% not a logical error it is a syntax error
This is the fiddle jsfiddle.net/kirtesh08/okbc5vb9 I dont know its not working properly but I explain the functionality when click on Second Level it pageId will go in textbox below permissions from there we can select the permissions and when on clcik of second page the permission will go as per selection
Even i tried u r code with mine code but its not toggleing the check box u can see the same code in fiddle
|
0

How do you link 'ChangeCheckBox()' to your button ? Can you post this code too ?

The problem is probably because the button refresh your page and so, the checkbox return to it initial state.

1 Comment

<a href=# onclick=ChangeCheckBox()>Change</a> I guess there is no refreshing problem

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.