Open In App

Set the value of an input field in JavaScript

In this article, we are going to learn how can we Set the value of an input field in JavaScript. We need to set the given input, in which the input will be provided by the input field and we need to display that input on the screen.

These are the following methods by using we can Set the value of an input field in JavaScript:



By using the innerHTML property

Example: This example is the implementation of the above-explained approach.






<!DOCTYPE html>
<html>
 
<head>
    <title>
        Set the value of an input field.
    </title>
</head>
 
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <input type='text' id='id1' />
    <br>
    <br>
    <button onclick="gfg_Run()">
        click to set
    </button>
    <p id="GFG_DOWN" style="color:green;
                            font-size: 20px;
                            font-weight: bold;">
    </p>
    <script>
        let el_down = document.getElementById("GFG_DOWN");
        let inputF = document.getElementById("id1");
 
        function gfg_Run() {
            inputF.value = "textValue";
            el_down.innerHTML =
                "Value = " + "'" + inputF.value + "'";
        }
    </script>
</body>
 
</html>

Output:

Set the value of an input field

By using setAttribute() method

Example: This example is the implementation of the above-explained approach.




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Set the value of an input field.
    </title>
</head>
 
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <input type='text' id='id1' />
    <br>
    <br>
    <button onclick="gfg_Run()">
        click to set
    </button>
    <p id="GFG_DOWN" style="color:green;
                            font-size: 20px;
                            font-weight: bold;">
    </p>
    <script>
        let el_down = document.getElementById("GFG_DOWN");
        let inputF = document.getElementById("id1");
 
        function gfg_Run() {
            inputF.setAttribute('value', 'defaultValue');
            el_down.innerHTML =
                "Value = " + "'" + inputF.value + "'";
        }
    </script>
</body>
 
</html>

Output:

Set the value of an input field


Article Tags :