如何从javascript中的文本输入字段中获取值?

时间:2017-02-09 12:13:55

标签: javascript html user-input

我尝试从用户那里获取输入的名字和姓氏,但我得到了他们两个未定义的结果。



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;
&#13;
&#13;

1 个答案:

答案 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>