1

I know that several questions about this topic have been asked, but I was unable to find an answer for my case.

I have a checked checkbox as

<input type="checkbox" name="text" checked="checked" />

I need to send ajax request by checking/unchecking, but I do not know what can be the reliable (with browser compatibility) for an if statement such as

if (this.value == 'on')
{
this.value = 'off';
ajax call;
}
else
{
this.value ='on';
ajax call;
}

Note that the value is not important here, and we need to catch checked/unchecked, but how control the checked element by JavaScript when the html original element has checked="checked"?

If using checked instead of value as

if (this.checked == true)
{
this.checked = false;
ajax call;
}
else
{
this.checked =true;
ajax call;
}

The tick of checkbox will not be changed in the browser (always ticked).

2 Answers 2

4

The following should work:

function myFunction(elem)
{
    if (elem.checked)
    {
        alert("Im Checked");
    }
    else
    {
        alert("Im not checked");
    }
}

Markup:

<input type="checkbox" name="text" checked="checked" onchange="myFunction(this);" />

http://jsfiddle.net/QMhn5/

Update: To change the check from other element:

document.getElementById("chk").checked = true;

or

document.getElementById("chk").checked = false;

Example: http://jsfiddle.net/QMhn5/1/

Sign up to request clarification or add additional context in comments.

1 Comment

How to check/uncheck?
1

If you can use jquery, this should work:

<input type="checkbox" id="c1" />


$("#c1").change(function(){
    var checked = $(this).is(":checked");
    console.log(checked);
    //ajax call
})

Fiddle: http://jsfiddle.net/XUgTC/ , try clicking the checkbox and look in the console.

3 Comments

I don't think the OP wants jQuery.
:) no need to apologize, I do that all the time.
@HanletEscaño yes I am attached to pure JS.

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.