javascript - 将表单值打印到 console.log 给出未定义的错误

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

我试图在提交给 console.log 时打印表单值以进行测试。但是收到未定义的消息。无法弄清楚我到底哪里出错了。我已经在 Whosebug 上浏览了各种答案,但仍然没有运气。这是代码 -

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>

您未定义,因为 forminput 不是单个对象它有多个 objects 而没有 属性 value.

您可以通过如下索引获取值

console.log(formInput[0].value);

您在输入值之前查询表单。脚本的第一行应该在事件侦听器中:

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

正在页面加载时查询这些值。您需要等到用户提交后再检查值。

你可以试试这个。希望对您有所帮助!

 function myFunction(){
  var a = document.getElementById("fullname").value;
  var b = document.getElementById("email").value;
  var c = document.getElementById("phn").value;

  console.log(a);
  console.log(b);
  console.log(c);

  return false;
 }
<form class="form-inline" onsubmit = " return myFunction()">
  <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>