Blog Archive

jQuery get Button value when clicked

How to get the button properties such as value, name, etc. on click event using jQuery

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. Here we are going to see how to query the HTML button element. We can attach each button using the id and listen for the click event or we can attach all the buttons on the HTML form and then query which one was clicked.Using jQuery we can very easily query the button element for its value and name.


jquery get button value when clicked


HTML source code for the application - index.html

<html>
<head>
<title>jQuery retrieve button properties such as name and value</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />

<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script type="text/javascript" src="app.js"></script>

</head>
<body>
 <div>
  Click on the button below to query its value ...<br /> <input
   id="button1" type="button" name="Button1 NAME" value="Button1 VALUE">
 </div>
 <div>&nbsp;</div>
 <div>
  Click on the button below to query its name ...<br /> <input
   id="button2" type="button" name="Button2 NAME" value="Button2 VALUE">
 </div>
</body>
</html>

jQuery source code for the application - app.js

$(document).ready(function() {

 $("#button1").click(function(event){
  alert($(this).prop("value"));
 });
 
 $("#button2").click(function(event){
  alert($(this).prop("name"));
 });

 //Alternate method to achieve the same result
 //comment the above logic and uncomment this
 $(":button").click(function(event){
  if($(this).prop("id") == "button1"){
   alert($(this).prop("value"));
  }
  else {
   alert($(this).prop("name"));
  }
 });

});