Button...">

Get the value of the pressed button

I have several buttons containing different values.

My buttons: -

<button id="1" name="1" value="1">Button1</button> <button id="2" name="2" value="2">Button2</button> 

Now, if I click Button1, I should get its value. This is 1 , and if I press Button2, I should get a value of 2 . I wrote this code: -

 <script type="text/javascript"> $("button").click(function() { var fired_button = $("button").val(); alert(fired_button); }); </script> 

But he always warns 1 . What should I do to fix my code?

+9
source share
8 answers

UPDATED

Use this instead of button in:

 var fired_button = $("button").val(); 

You should use this to target the currently pressed button instead of button , which will select all the buttons in the DOM, .val () will force it to get the value of the first button.


 $("button").click(function() { var fired_button = $(this).val(); alert(fired_button); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="1" name="1" value="1">Button1</button> <button id="2" name="2" value="2">Button2</button> 
+11
source

You can try something simple:

 $(this).val(); 

 $(function(){ $("button").click(function() { var fired_button = $(this).val(); alert(fired_button); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="1" name="1" value="1">Button1</button> <button id="2" name="2" value="2">Button2</button> 

Note. After the document is ready, you must add event listeners. This is why I turned on the event handler in

 $(function{}) 

This is short for

 $(document).ready(function(){}) 

For more information about this, please see here .

+2
source

To access the value of the button pressed, you need to use the this variable.

 <script type="text/javascript"> $("button").click(function() { var fired_button = $(this).val(); alert(fired_button); }); </script> 

This will return the value button of the button.

+2
source

Use this inside the click handler.

 <script type="text/javascript"> $("button").click(function() { var fired_button = $(this).val(); alert(fired_button); }); </script> 
+1
source

this will give you the element that was clicked, $(this) to get the jquery version.

Update your code to:

 $("button").click(function() { var fired_button = $(this).val(); alert(fired_button); }); 
+1
source

Try with $(this).val(); . It will return the value of the click button.

+1
source

Try $(this).val() . 'this' always refers to the current object.

0
source

If you use jQuery, you need the .attr () function.

 $(this).attr("value") 

This code will give you the value attribute of the html element created by $ (this) (or you specify the element identifier).

0
source

All Articles