How to change and retrieve HTML form values using jQuery

We can use jQuery to change and retrieve HTML form element values. There is val() method available for this purpose. The val() function allows us to change and retrieve any HTML form elements' value in very easy way. Example is mentioned below: val() method example


<html>
<head>
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="textElem" value="Sample Text"><br>

    Color<br>
    <input type="radio" name="colorElem" value="Red Color" checked>Red Color
    <input type="radio" name="colorElem" value="Green Color">Green Color
    
    <br>
    <button id="btnGetValue">Get Value</button>
    <button id="btnSetValue">Set Value</button>

    <script>
        $(document).ready(function () {
            $('#btnGetValue').on('click', function () {
                // Get val of checked radio button
                alert($("input:radio[name=colorElem]:checked").val());
                alert($("#textElem").val());
            });

            $('#btnSetValue').on('click', function () {
                $("#textElem").val('Programming World');
            });
        });
    </script>
</body>
</html>