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?
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 .