22

I have been trying to make a simple app with 3 fields like this:

    <div id = "nameInput" >Name:</div><input id = "nameInputField" type = "text" name = "userName" />
    <div id = "emailInput" >Email:</div><input id = "emailInputField" type = "text" name = "email" />
    <input id = "termsCheck" type = "checkbox" name = "terms" />

The problem I am having is that I keep needing to try to wrap it in a form to get the checkbox to register as checked when it is. I DO NOT want to use a form because I don't ever want to submit anything.

Here is the JS for the checkbox as well. It is always marked as unchecked:

if ($('#terms').checked == true) {
    //Rest of code

Is there a way to make this without using a form or is there a reason that my checkbox is never registered as checked?

4
  • I am assuming you are using jQuery based on the code in your question Commented May 18, 2011 at 18:38
  • why would you NOT want to use a form? input is defined to always be part of a form Commented May 18, 2011 at 18:38
  • I keep getting issues with the form always submitting. I thought it would be easier without a form. I was also curious if it was possible Commented May 18, 2011 at 18:41
  • 1
    You could always wrap it in a form and not include a submit button. Commented May 18, 2011 at 18:42

5 Answers 5

26
<input id = "termsCheck" type="checkbox" name="terms" />

JS:

pre jQuery 1.6:

if($('#termsCheck').is(':checked')){}

after jQuery 1.6:

if($('#termsCheck').prop('checked')){}
Sign up to request clarification or add additional context in comments.

Comments

4

Two issues.

First, you're referencing the name of the input instead of its ID.

Second, in order to use the checked property, it must be done on the DOM element, not the jQuery object.

if( $('#termsCheck')[0].checked ) {
    // ...
}

This is accessing the DOM element at index 0 of the jQuery object, then accessing its checked property.

You could also use the get()[docs] method to retrieve the DOM element.

if( $('#termsCheck').get(0).checked ) {
    // ...
}

Comments

4

If you DON'T want to use jQuery, you could do something like:

<input id = "termsCheck" type = "checkbox" name = "terms" />

and refer to it this way:

if (document.getElementById("termsCheck").checked) {
}

1 Comment

If you change getElementByID to getElementById it works perfectly fine
1

You need to check the checked state differently

$('#terms').is(":checked")

Comments

1

the jquery object (witch im asuming your using) dosent have an checked field so that fill be false yes

what you can do is

 $("#terms").is(":checked")

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.