I'm using the following code to loop through all the checkboxes in my form. The boxes are gerenated dynamicaly from a php script so I won't know the names or the number of check boxes.
I need to find out which checkboxes have been ticked so I only pass those ones to the php script that handles the form.
$("#panelform input:checkbox").each(function () {
if(this.is(":checked")){
fields = fields+"&"+this.name+"="+this.value;
}
});
When the script gets to the this.is(":checked") it errors but being jquery my console doesn't show me any error messages just stops.
if I alert or console.log "this" after the first line I get the form field so I know that that much works.
I'm using the following code to loop through all the checkboxes in my form. The boxes are gerenated dynamicaly from a php script so I won't know the names or the number of check boxes.
I need to find out which checkboxes have been ticked so I only pass those ones to the php script that handles the form.
$("#panelform input:checkbox").each(function () {
if(this.is(":checked")){
fields = fields+"&"+this.name+"="+this.value;
}
});
When the script gets to the this.is(":checked") it errors but being jquery my console doesn't show me any error messages just stops.
if I alert or console.log "this" after the first line I get the form field so I know that that much works.
Share asked Jan 14, 2013 at 15:49 flyersunflyersun 9173 gold badges16 silver badges35 bronze badges 2-
What do you mean "being jquery my console doesn't show me any error messages"? You should have seen something like
Uncaught TypeError: Object #<HTMLInputElement> has no method 'is'
– No Results Found Commented Jan 14, 2013 at 15:52 - JavaScript errors show up in the console even if you are using jQuery. The browser doesn't know/care what frameworks you use. – Álvaro González Commented Jan 14, 2013 at 15:54
4 Answers
Reset to default 5try with
if($(this).is(":checked")){
since this
is just a reference to the node in the DOM (and you need instead to use the jQuery
wrapper to chain the method is()
.
Try this:
if( this.checked)
this
is the plain DOM node, checked
is its property to tell you if it's checked or not. Creating a whole new jQuery object just to see if a property is set is redundant.
In that contect, this
refers to the DOM element, not the jQuery object - and DOM elements have no method is()
. You can wrap it in a jQuery object if you want to use is method:
if($(this).is(":checked")){
or use the DOM Element's checked
property:
if(this.checked){
$(this).is(':checked')
if you want to serialize your form try this
$('your-form-selector').serializeArray()