1

Hi i have got a checkbox and when i click it and check the box a function runs, which works just how i want it to.. now i want to run a DIFFERENT function if it is checked off but it is just running the same function everytime.

<input type="checkbox" class="no-custom" onclick="CheckBox()">
function CheckBox() {
    $("#emailMain").css({"display": "none"});
    $("#emailSame").css({"display": "inline"});
    var Mainemail = Customer().email['#text']();
    Contact().email = Mainemail;
    EmailHolder(Mainemail);
}

Any ideas in the best way to sort this?

3 Answers 3

3

Firstly, if you've included jQuery in your page you should use it to attach your events as its a better separation of concerns. You can then use the checked property of the element to determine which function to call:

<input type="checkbox" class="no-custom" />
$('.no-custom').change(function() {
    if (this.checked) {
        // do something...
    }
    else {
        // do something else...
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Love this answer.. just getting to grips with jquery and i want to use best practice and this works great. Thanks
0

Add an ID to the checkbox:

<input type="checkbox" id="the-checkbox" class="no-custom" onclick="CheckBox()">

Then add an event listener for when it changes:

$(function() {

    $('#the-checkbox').change(function() {

        if($(this).is(':checked')) {
            oneFunction();
        }
        else {
            anotherFunction();
        }

    });

    function oneFunction() {

    }

    function anotherFunction() {

    }

});

Comments

0

You can easily check if the checkbox is checked using jQuery is.

<input type="checkbox" class="no-custom" onclick="CheckBox(this)">

function CheckBox(cb) {
  if ($(cb).is(":checked")) {
    alert("Checked");
    CheckedFunction();
  } else {
    alert("Unchecked");
    UncheckedFunction
  }
}

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.