开发者

Passing Value to Javascript function

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.

  1. Using alert() for debugging. This is almost always worse than using console.log(). Everything passed to alert is converted to a string, which is why you see "[object Object]" instead of something useful. Switch to console.log() and you'll see something meaningful.
  2. jQuery event callbacks are passed a jQuery event object. That object is what id is set to.
  3. The inline onclick handler has absolutely nothing to do with the change 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜