I'm calling a jQuery function, but the alert function displays [object Object]. The c开发者_运维百科heck value works, but not the passed id value.
Here's the call to the function taken from the html output:
<td class="myGroups">
<input class="chkSubscribed" type="checkbox" onclick="UpdateSubscription(2)" name="subscribed">
</td>
Here's the javascsript function:
$(".chkSubscribed").change(function(id) {
alert(id);
var chkd=0;
var groupid=id;
if (this.checked) { chkd=1; }
$.ajax({
type:"POST",
url:"resources/updateSubscribe.php",
data: { group_id: groupid, checkval: chkd },
success: function(){
alert("Account updated!" + "chkval=" + chkd + " id=" + groupid); }
});
});
Thanks for any help!
You're doing it wrong.
Either you want to call a function or you want to use the change event.
If you want to call a function create a function as follows:
function moo(id) {
//code here
}
If you want to do it using the change event you can give your input an id of the number you want as follows:
<input id="2" class="chkSubscribed" type="checkbox" name="subscribed">
And then your javascript should look as follows:
$(".chkSubscribed").change(function() {
id=this.id;
//and the rest of the code as you wrote
});
There are a few different issues at play here.
- Using
alert()
for debugging. This is almost always worse than usingconsole.log()
. Everything passed toalert
is converted to a string, which is why you see"[object Object]"
instead of something useful. Switch toconsole.log()
and you'll see something meaningful. - jQuery event callbacks are passed a jQuery
event
object. That object is whatid
is set to. - The inline
onclick
handler has absolutely nothing to do with thechange
handler that you've bound with jQuery.
the jQuery function change()
will pass the event object, not the id of the changed object - you treat it as if it was the id currently.
精彩评论