通过javascript获取表单字段数据抛出错误(值为null)

function myFunc() {

  console.log("entered");

  document.write('Submitted Data');

  var firstname = document.getElementById("fname").value;

  var lastname = document.getElementById("lname").value;

  document.writeln("Your full name is:" + firstname + lastname);

}

<form>

  <label> Firstname </label>

  <input type="text" name="firstname" id="fname" size="15" /> <br> <br>

  <label> Lastname</label>

  <input type="text" name="lastname" id="lname" size="15" /> <br> <br>

  <label>   

    Gender :  

    </label><br>

  <input type="radio" name="male" /> Male <br>

  <input type="radio" name="female" /> Female

  <br>

  <br>

  <input type="button" value="Submit" onclick="myFunc()" />

</form>

单击提交后,它不会获取名字并在控制台中显示错误值 null。有人可以帮忙吗?整个代码保存在一个 HTML 页面中



长风秋雁
浏览 150回答 1
1回答

月关宝盒

那是因为这条线document.write('Submitted Data');。document.write删除现有的 html,以便在您使用的下一行中document.getELementById找不到 dom 元素function myFunc() {&nbsp; var firstname = document.getElementById("fname").value;&nbsp; var lastname = document.getElementById("lname").value;&nbsp; document.writeln("Your full name is:" + firstname + lastname);}<body bgcolor="Lightskyblue">&nbsp; <br>&nbsp; <br>&nbsp; <form>&nbsp; &nbsp; <label> Firstname </label>&nbsp; &nbsp; <input type="text" name="firstname" id="fname" size="15" /> <br> <br>&nbsp; &nbsp; <label> Lastname</label>&nbsp; &nbsp; <input type="text" name="lastname" id="lname" size="15" /> <br> <br>&nbsp; &nbsp; <label>&nbsp; &nbsp;&nbsp; &nbsp; Gender :&nbsp;&nbsp;&nbsp; &nbsp; </label><br>&nbsp; &nbsp; <input type="radio" name="male" /> Male <br>&nbsp; &nbsp; <input type="radio" name="female" /> Female&nbsp; &nbsp; <br>&nbsp; &nbsp; <br>&nbsp; &nbsp; <input type="button" value="Submit" onclick="myFunc()" />&nbsp; </form></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript