Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




HTML METHODS - val()


The val() method is used to get and set the value of an HTML form element.


val() as Getter method


Example :



<html>
  	<head>
    	<title> My First Programme </title>
    	
    	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	Enter anything and click to get its content : <input type = "text"/>
        
        <br/><br/>
        
        <button> Click it </button> 
	  
      	<script>
      
			$('button').click( function() { 
            	alert($('input').val());
            });
            
      	</script>      
  	</body>
</html>


Output :




So, if we look at the above code, we have an <input> element(Just remember, <input> element is a part of the <form> element).


<input type = "text"/>

And we have a <button> element,


<button> Click it </button>

And on buton click, the JQuery statement gets triggered,


$('button').click( function() {
	alert($('input').val());
});

And an alert is generated,


alert($('input').val());

Now, if we see the output (i.e. The alert),


You get that value which you have entered in the <input> field.


This is because the val() method is used to get the actual value of the <input> element.


val() as Setter method


Example :



<html>
  	<head>
    	<title> My First Programme </title>
    	
    	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	Click on the below button to set value to 'Hello World' : <input type = "text"/>
        
        <br/><br/>
        
        <button> Click it </button> 
	  
      	<script>
      
			$('button').click( function() { 
            	$('input').val('Hello World');
            });
            
      	</script>      
  	</body>
</html>


Output :




So, if we look at the above code, we have an <input> element(Just remember, <input> element is a part of the <form> element).


<input type = "text"/>

And we have a <button> element,


<button> Click it </button>

And on button click, the JQuery statement gets triggered,


$('button').click( function() {
	$('input').val('Hello World');
});

And if you see the above output, the content of the <input> element gets changed to Hello World.


This is because the val() method is used to set the value of the <input> element to Hello World.


$('input').val('Hello World');