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开发者_StackOverflow 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?
<input id = "termsCheck" type="checkbox" name="terms" />
JS:
pre jQuery 1.6:
if($('#termsCheck').is(':checked')){}
after jQuery 1.6:
if($('#termsCheck').prop('checked')){}
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 ) {
// ...
}
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) {
}
You need to check the checked state differently
$('#terms').is(":checked")
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")
精彩评论