2

我想知道以下内容为什么会给我带来麻烦,它看起来很简单,但我不确定发生了什么。

所以我有一个输入框,我希望用户填写它,每次我运行以下

我身份不明,我不知道为什么。

<input type="numbers" name="price" class="sell" placeholder="$0.00">

我正在使用以下 javascript

var price = document.getElementsByName("price")
    alert(price.value);
4

2 回答 2

4
var price = document.getElementsByName("price")[0];
    alert(price.value);

document.getElementsByName will give you HTMLCollection (kind of array) as a return type. This is because a number of elements in your dom may share the same name. So if you have number of checkboxes having same name you can refere each checkbox with the array index.

于 2012-07-18T10:16:02.857 回答
4

You have several problems.

The one causing your problem is that getElementsByName returns an HTMLCollection (which is like an array), not a single element. You need to pull the first item off it before trying to access its properties.

var price = document.getElementsByName("price")[0];

Second, numbers it not a type of input. number (singular) is.

Third, if you give the example $0.00 then you are informing people that you expect them to type a value starting with a $ sign. You can't have a $ sign in a number.

于 2012-07-18T10:16:46.570 回答