jQuery val method

Hello guys,

In this article, we will learn how you can get value from the form fields and set the value. This is important when you want to use Ajax, to get specific input value.

jQuery val() method is used to get current value or set new value to form elements.

Syntax:

$(selector).val();

Or 

$(selector).val(newValue);

Here is the example to get value from input element.

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <h1 class="m-3">jQuery val() function</h1>
    <div class="row">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" value="John Doe">
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var nameValue = $('#name').val();
            alert(nameValue);
        });
    </script>
</body>
</html>

In the same way, you can also set new value to form fields. Here is the example how to set new value to textarea.

<!doctype html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <h1 class="m-3">jQuery val() function</h1>
    <div class="row">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <textarea class="form-control w-50" id="name">John Doe</textarea>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#name').val('Sara Jay');
        });
    </script>
</body>
</html>

The val() method can can be also used to get and set value in select tag. Here is example how to get and set value to select tag. 

<select id="month">
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3" selected>March</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        console.log($('#month').val()); // 3
        $('#month').val('2');
        console.log($('#month').val()); // 2
    });
</script>

This way, you can get existing value and set new value to form fields.

Tags: