ross ross - 7 days ago 5
HTML Question

javascript - printing form values to console.log giving undefined error

I was trying to print form values on submit to console.log to test. But getting a undefined message. Can't figure out where I am going wrong exactly. I have gone through various answers on StackOverflow but still no luck. Here is the code -

HTML

<form class="form-inline">
<label class="required">* required </label>
<div class="form-group">
<input type="text" class="form-control inputArea" id="fullname" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="email" class="form-control inputArea" id="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="tel" class="form-control inputArea" id="phn" placeholder="Phone Number *">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>


JavaScript

<script>
var formInput = document.querySelectorAll('#fullname, #email, #phn');

document.querySelector('form.form-inline').addEventListener('submit', function (e) {
e.preventDefault();
console.log(formInput.value);
});
</script>

Answer

You are querying the form before the values are inputted. The first line of your script should be inside the event listener:

<script>
    document.querySelector('form.form-inline').addEventListener('submit', function (e) {
        e.preventDefault();
        var formInput = document.querySelectorAll('#fullname, #email, #phn');
        console.log(formInput.value);
    });
</script>

The values are being query-ed on page-load. You need to wait until the user submits before you check the values.

Comments