What Is The Use Of Val Method In JQuery With Example

admin_img Posted By Bajarangi soft , Posted On 16-10-2020

In JQuery we can use val method to read values of html elements So today we discuss how to use it

What Is The Use Of Val Method In JQuery With Example

Step 1:Create index.html file and implement below code.

<input  class="form-control" type="text" name="first_name" value="John" id="first_name"><br><br>
<input  class="form-control" type="text" name="first_name" value="Deo" id="last_name"><br><br>
<button class="btn btn-success" id="get">GET Value</button>
<button class="btn btn-success" id="set">SET Value</button>

Step 2:Implement jQuery to Val() methods.
 
<script>
    $(document).ready(function(){
        $("#get").click(function(){
            var first_name=$("#first_name").val();
            var last_name=$("#last_name").val();
            alert(first_name + " " +last_name);
        });
        $("#set").click(function(){
            $("#first_name").val("Larry");
            $("#last_name").val("Hen");
        });
    });
</script>

Complete Code For Using html() Method In JQuery 
<!DOCTYPE html>
<html>
<head>
    <title>What Is The Use Of Val Method In JQuery With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: black;
    }

    .error {
        color: red;
    }
</style>
<body>
<div class="container">
    <br><br><br><br>
    <div class="text-center">
        <h1 id="color" style="color: White;">Val() Method In JQuery</h1>
    </div>
    <br>

    <div class="well">
        <input  class="form-control" type="text" name="first_name" value="John" id="first_name"><br><br>
        <input  class="form-control" type="text" name="first_name" value="Deo" id="last_name"><br><br>
        <button class="btn btn-success" id="get">GET Value</button>
        <button class="btn btn-success" id="set">SET Value</button>
    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("#get").click(function(){
            var first_name=$("#first_name").val();
            var last_name=$("#last_name").val();
            alert(first_name + " " +last_name);
        });
        $("#set").click(function(){
            $("#first_name").val("Larry");
            $("#last_name").val("Hen");
        });
    });
</script>

Related Post