无法通过.value从输入中获取值

时间:2016-07-14 19:09:17

标签: javascript

我无法弄清楚为什么.value不起作用。我也尝试过.querySelector而不是.getElementById,但我在控制台中一直未定义。



var submit = document.querySelector('#submit');
var name = document.getElementById('ship-name');

submit.onclick = function() {
  console.log(name.value);
};

<div class="box">
  <h2>Where do you want your stuff sent?</h2>
  <label for="ship-name">
    <input class="full text-input" id="ship-name" type="text" placeholder="Name" required>
  </label>
  <label for="ship-add-1">
    <input class="full text-input" id="ship-add-1" type="text" placeholder="Address Line 1" required>
  </label>
  <label for="ship-add-2">
    <input class="full text-input" id="ship-add-2" type="text" placeholder="Address Line 2" required>
  </label>
  <label for="ship-add-3">
    <input class="full text-input" id="ship-add-3" type="text" placeholder="Address Line 3" required>
  </label>
  <label for="ship-4">
    <input class="full text-input" id="ship-add-4" type="text" placeholder="Address Line 4" required>
  </label>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

将.js文件中的代码更改为:

document.getElementById('submit').onclick = function () {
 console.log(document.getElementById('ship-name').value);
}

正如评论中提到的那样,你滥用全球空间。

另外,请记住在引用的html之后包含脚本。

答案 1 :(得分:0)

谢谢大家。大卫H的答案解决了这个问题。我只是将变量名称更改为其他内容并且有效。他是对的,你不能在全局范围内拥有一个名为name的变量。

答案 2 :(得分:-2)

你试过吗?

var name = $('#ship-name').val();

然后

console.log(name);
相关问题