jQuery .val


The .val() method is used to get the current value of the FIRST element in the set of matched elements. The .val is frequently used to get the value of the input in a form. But it can also be used to extract the values in select and textarea elements ( And also to access the values of input checkbox and input radio buttons).



<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js">
</script>
<script>
$(document).ready(function(){
  $("input").blur(function(){
    var msg ="Hello "; 
    var x = $("input").val();
   $("span#id1").html(msg+x);
  });
});
</script>
</head>
<body>

<input type="text">
<br />
<span id ="id1">Enter Your name</span> <br />
</body>
</html>



This example asks you to enter your name in an input area. Your name is captured in using the blur function ( as soon as you remove your mouse from the input area. The Captured name is then displayed to give you a impressive response.
You may like to try this example here.

This example could potentially be extented to check the validity of form giving a green right or a red cross as depending upon if the input is entered correctly or not.

If you have more than one imput field, you could differentiate them by using their ids. The following example shows one way of doing it, where we have captured the name and the age in two different fields.



<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js">
</script>
<script>
$(document).ready(function(){
  $("input#name").blur(function(){
    var msg ="Hello "; 
    var x = $("input#name").val();
   $("span#id1").html(msg+x);
  });
  $("input#age").blur(function(){
    var msg ="You are "; 
    var y = $("input#age").val();
   $("span#id2").html(msg+y +" Years old");
  }); 
 
});
</script>
</head>
<body>

<input id ="name" type="text"><span id ="id1">Enter Your name</span><br /><br />
<input id ="age" type="text"> <span id ="id2">Enter Your age</span> <br />
</body>
</html>




You may like to try this example here.