Difference between val() and text()

Difference between val() and text()

What the difference between jQuery’s functions val() and text()?
Where would you use one over the other?

Solutions/Answers:

Solution 1:

.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

Solution 2:

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)

Related:  What does two colons inside an angular expression {{::}} mean?

according to the official documentation text() should not be used with input elements

Solution 3:

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>