DEV Community

Dhruv Raval
Dhruv Raval

Posted on • Originally published at dhruvraval.dev on

How do I get the value of text input field using JavaScript?

You can use onkeyup when you have more than one input field. Suppose you have four or input. Then "document.getElementById('something').value" is annoying. We need to write four lines to fetch the value of an input field.

So, you can create a function that store value in object on keyup or keydown event.

Example:

<div class="container">
    <div>
        <label for="">Name</label>
        <input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Age</label>
        <input type="number" name="age" id="age" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Email</label>
        <input type="text" name="email" id="email" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Mobile</label>
        <input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
    </div>
    <div>
        <button onclick=submitData()>Submit</button>
    </div>
</div>

<script>
    const data = { };

    function handleInput(e){
        data[e.name] = e.value;
    }

    function submitData(){
        console.log(data.fname); // Get the first name from the object
        console.log(data); // return object
    }
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)