Jump to content

Alert buttons ID shows 'undefined'


slj90
Go to solution Solved by Ch0cu3r,

Recommended Posts

I'm using PHP to echo out a button within a loop along with other data.
 

... <input id="delete' . $row[item_generated_id] . '" type="button" class="btn btn-danger" value="Delete" onclick="DeleteItemByID()"'; echo '">...

I then want the function to alert the buttons ID...

 

function DeleteItemByID() {
var deleteid = $(this).attr('id');
alert(deleteid);
}

However, it is currently only alerting 'undefined'. What's wrong?

 

Having the button alert it's ID is obviously not my final objective but it will help me.

 

Thanks!

Link to comment
Share on other sites

  • Solution

Probably because $(this) is only defined by jquery if it is handling the click event. Jquery only handles events you instruct it to do.

 

Either have Jquery handle the onclick event (using its event handler) or pass  this  as the argument to the function being called in the onclick attribute  onclick="DeleteItemByID(this)". Setting  this  as the argument passes the event instance of the element that was clicked to the function.

 

Now in your function will be

function DeleteItemByID(elm) {
  var deleteid = elm.id; // get the id attribute from the element instance from where this function was called from
  alert(deleteid);
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.