Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between val and text in jquery.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 992
    Comment on it

     text

    This attribute is used to set or return the text content of the elements which are selected. HTML markup is removed when this attribute is used to return text content i.e returns that text content that can be displayed in the browser while setting text content, the content of all matched element is overwritten. 

     val

    This attribute is used to set or return value of html element. Setting value of an element means value attribute of all matched element is set while returning value means value attribute of first matched element is returned.

    Program to demonstrate text() and val() method:

    <!DOCTYPE html>
    <html>
    <head>
      <title>jQuery With Example</title>
      <script src="http://code.jquery.com/jquery-1.9.1.js" 
    
    type="text/javascript"></script>
      <script type="text/javascript">
        $(function () {
          $("#btnClick").click(function () {
            $("#div1").text($("#Container").text());
            $("#div2").text($("#txtCountry").val());
          });
        });
      </script>
    </head>
    <body>
      <div id="Container">
        <b>Country</b>
        <input type="text" id="txtCountry" value="India" />
      </div>
      <button id="btnClick">Click</button>
    <div id="div1"></div>
    <div id="div2"></div>
    </body>
    </html>

    Output:

    On click of button the output will be:

    Country

    India

    Explanation:

    In above program when button is clicked text content of ( #Container").text() i.e returned text content is written in div1 i.e seting text content of div1. The text content within container is only Country that can be displayed in browser without html markup. The value attribute of txtCountry $("#txtCountry").val()  is wriiten in div2. The value of  txtCountry is India.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: