Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  104] [ 5]  / answers: 1 / hits: 156998  / 9 Years ago, tue, september 29, 2015, 12:00:00

I have multiple 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 on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-



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


But it always alerts 1. What must I do to fix my code?


More From » jquery

 Answers
93

UPDATED



Use this instead of button in :



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


You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes 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>




[#64904] Friday, September 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregoriocoya

Total Points: 549
Total Questions: 111
Total Answers: 104

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;