Search

How to get and set Value in Form Fields in Javascript

post-title

In this article, we will discuss on setting and getting value from input and textarea. These elements contains value and not text. So first, let's starting with getting value from input field.

Let's get value from input field.

Example:

<input type="text" id="message" name="message" value="Hello World!">
<script type="text/javascript">
    var data = document.getElementById('message').value;
    console.log(data);
</script>

Same way we can also set value in the field. Here is example of textarea field.

Example:

<textarea id="message" name="message">Hello World!</textarea>
<script type="text/javascript">
    var data = document.getElementById('message').value = 'Hello Earth!';
    console.log(data);
    // Hello Earth!
</script>

This will change text value in textarea field. Now let's look at how to get value from radio button. This is something different than textarea or input field. In the radio button, we have multiple input but we only need the checked input value.

Example:

<input type="radio" id="male" name="gender" value="male"><label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female"><label for="female">Female</label>
<button onclick="checked()">Click</button>
<script type="text/javascript">
    function checked() {
        var data = document.querySelector("input[name=gender]:checked").value;
        console.log(data);
    }
</script>

In the checkbox field, value is already there, all we have to do is to check whether the checkbox is checked or unchecked. checked property will return true if element is checked. This is how we can do it.

Example:

<input type="checkbox" id="remember" name="remember" value="true"><label for="remember">Remember me?</label>
<button onclick="checked()">Click</button>
<script type="text/javascript">
    function checked() {
        if (document.querySelector("input[name=remember]").checked) {
            var element = document.querySelector("input[name=remember]").value;
            console.log(element);
        } else {
            console.log(false);
        }
    }
</script>

Conclusion

So far in this article, we have learned how to get and set value to different input and textarea.

I hope this will help you.