slj90 Posted October 29, 2015 Share Posted October 29, 2015 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! Quote Link to comment https://forums.phpfreaks.com/topic/298909-alert-buttons-id-shows-undefined/ Share on other sites More sharing options...
Solution Ch0cu3r Posted October 29, 2015 Solution Share Posted October 29, 2015 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); } Quote Link to comment https://forums.phpfreaks.com/topic/298909-alert-buttons-id-shows-undefined/#findComment-1524727 Share on other sites More sharing options...
slj90 Posted October 29, 2015 Author Share Posted October 29, 2015 Thank you! Quote Link to comment https://forums.phpfreaks.com/topic/298909-alert-buttons-id-shows-undefined/#findComment-1524740 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.