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



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

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>

您正在按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>

相关内容

  • 没有找到相关文章

最新更新