What the difference between jQuery\'s functions val()
and text()
?
Where would you use one over the other?
val() is used to fetch value from all html input types like(checkbox,text,etc),where user have an option to input value. Ex:-
<input type="text" id="txt_name" />
<input type="checkbox" name="vehicle" value="Bike" id="chk_byk" class="ss">bike<br>
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").click(function () {
alert($("#chk_byk").val());
});
});
</script>
where as text() is used to fetch value from the html elements where user will not interact like (p,div etc)
<p id="p1">Hi how are u??</p>
<div id="dv5">Debendra</div>
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").click(function () {
alert($("#dv5").text());
});
});
</script>
.val() function returns value from input element and .text() function returns value from other than input elements. We can also pass string argument to these functions to set the value of the calling element. Below code shows how to set value to DOM elements using .val() and .text() functions:
HTML Part:
<form id="form1"><input id="first" type="text" /><input type="submit" /></form>
<div id="second">Click the "Submit Query" to see it work</div>
Jquery Part:
$(document).on("submit", "form", function (e) {
$("#first").val("This input is set by .val() function");
$("#second").text("A new text is set using .text() function!");
return false;
})
Demo: http://jsfiddle.net/urhys9zj/6/
text() return the combined text contents of all matched elements (such as p, div, and so on) val() is used to obtain the value of an input element (such as input, select, and so on)
according to the official documentation text() should not be used with input elements
.val()
works on input elements (or any element with a value attribute?) and .text()
will not work on input elements. .val()
gets the value of the input element -- regardless of type. .text()
gets the innerText (not HTML) of all the matched elements:
.text()
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.
.val()
Get the content of the value attribute of the first matched element