May 4, 2011

how to determine which button has been clicked in jquery

Question by Kyokasuigetsu

I’m using a php loop to generate multiple button elements. How can I determine which button has been clicked by using jquery?

<script type="text/javascript">

$(function(){

    if(button.click){
        alert(button.id);
    }

});

</script>

<?php for($x=0; $x<4; $x++){ ?>
<ul id="x">
<li><input type="button" id="<?php echo $x; ?>" value="<?php echo $x; ?>"/></li>
</ul>
<?php } ?>

Answer by Starx

The most common way to identify a element is id. (Literally, id does mean "identification")

The way you want it, should be something like this.

$("input").click(function() { //This will attach the function to all the input elements
   alert($(this).attr('id')); //This will grab the id of the element and alert. Although $(this).id also work, I like this way.
});

However, generalizing the bind to all the input elements might be a bad idea. So try giving a common class to specific elements and use $(".yourclass") instead.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!