Getting the Value of the Inputted Field using JQUERY and Display the Results

Guest Posts Paolo Nikko Nuñal

With the power of JQUERY, getting the value of input boxes are as easy as doing it on Javascript or HTML form submit function using a button. This is very important if you are want to get the value of the input box and processing it through Javascript. Here's how you do it.

Code


<h4>Name:</h4><input id="input1">
<h4>Address:</h4><input id="input2">
<h4>Number:</h4><input id="input3">
<button type="button" id="btn1">Get First Name</button>
<button type="button" id="btn2">Get Address</button>
<button type="button" id="btn3">Get Number</button>
<script>
$("#btn1").click(function(){
   var name    = $("#input1").val(); 
   alert(name);
});
$("#btn2").click(function(){
   var address = $("#input2").val();
   alert(address);
});
$("#btn3").click(function(){
   var number  = $("#input3").val();
   alert(number);
});
</script>






Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here



Explanation


For the code, always remember that JQUERY already has built in functions that can easily select an DOM element. For the example code above, when the user clicks on "Get First Name" anything that a user inputs in the "Name" field will automatically be displayed.

$("#btn1").click(function(){ });- is a function that to "listen" the button with the id "btn1". So every time a user clicks on the "Get First Name" button, anything under the function will be processed. In our case, we get what's inside the input field and output it with the use of the alert function. In getting the value of the input field we use the function val().

The val() function is used to get the value of the input field and assigned it to the variable "name". Afterwhich we displayed the value that we got through the use of the alert function.