我尝试从用户那里获取输入的名字和姓氏,但我得到了他们两个未定义的结果。
function getTextField() {
var fname = document.getElementsByClassName("fname").value;
var lname = document.getElementsByClassName("lname").value;
var message = fname + "\n" + lname;
document.getElementsByClassName("get")[0].innerHTML = message;
}

<form name="cost" autocomplete="on">
First Name:
<br>
<input type="text" name="fname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25">
<br>Last Name:
<br>
<input type="text" name="lname" required placeholder="Enter the last name" pattern="[A-Za-z\-]+" maxlength="25">
<br>
<br>
<input type="button" onClick="getTextField()" value="Place Order!" />
<br>
<br> <span class="get"></span>
</form>
&#13;
答案 0 :(得分:2)
您正在按class
而不是name
属性查找名称字段。
使用getElementsByName
代替getElementsByClassName
function getTextField() {
var fname = document.getElementsByName("fname")[0].value;
var lname = document.getElementsByName("lname")[0].value;
var message = fname + "\n" + lname;
document.getElementsByClassName("get")[0].innerHTML = message;
}
<form name="cost" autocomplete="on">
First Name:
<br>
<input type="text" name="fname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25">
<br>Last Name:
<br>
<input type="text" name="lname" required placeholder="Enter the last name" pattern="[A-Za-z\-]+" maxlength="25">
<br>
<br>
<input type="button" onClick="getTextField()" value="Place Order!" />
<br>
<br> <span class="get"></span>
</form>