jQuery val() Method
jQuery offers various methods for manipulating the HTML and CSS. The jQuery val() method operates on the input value (the text entered or item selected) .val() actually serves two functions — get the current value of the first element in the set of matched elements or set the value of every matched element.Get the Values of Text Fields with val() method
var content = $("#getVal").val();
alert(content);
<input id="getVal" type = "text" value = "Textbox 1 Value"/>
Set the Values of Text Fields with val() method
$("#btnSet").click(function(){
$("#setVal").val("New Text added here...");
});
<input id="setVal" type = "text" value = "Textbox 2 Value"/>

<html>
<head>
<title>jQuery val() method example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btnGet").click(function(){
var content = $("#getVal").val();
alert(content);
});
$("#btnSet").click(function(){
$("#setVal").val("New Text added here...");
});
});
</script>
</head>
<body>
<button id="btnGet">Get Val</button>
<button id="btnSet">Set Val</button></br>
<input id="getVal" type = "text" value = "Textbox 1 Value"/><br/>
<input id="setVal" type = "text" value = "Textbox 2 Value"/>
</body>
</html>
When do I use .val() vs .html?
The .val() method is used to get/replace input elements values in jQuery while .html() method is used to get/replace the whole markup inside an element, not input elements.
Related Topics