弹出警报用户在文本框中写的内容

问题描述

我在大学里做运动,但被困住了。我想制作一个页面,通过按“搜索”按钮将显示一个弹出窗口(警告),其中包含“学生ID”的文本框的内容,而按“插入”按钮将显示一个弹出窗口(警报),其中包含“名字”的文本框内容

这是我的代码

<html>
<body>
<form action="/action_page.PHP">
<label for="studentid">Student Id:</laber><br>
<input type="text" id="studentid" name="studentid"><br>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br><br>
<button type="button">Search</button>
<button type="button">Insert</button> 
</form>
</body>
</html>

解决方法

编辑HTML使其包含在按钮中:

<button type="button" onclick="search()">Search</button>
<button type="button" onclick="insert()">Insert</button>

并将其添加到末尾:

<script>
function search() {
    let studentID = document.querySelector("#studentid").value;
    alert(studentID);
}
function insert() {
    let firstName = document.querySelector("#fname").value;
    alert(firstName);
}
</script>

此HTML代码将分别在单击时运行javascript函数“ search()”或“ insert()”,这些操作将执行以下操作:

  1. 创建一个变量,并为其分配“ studentid”或“ fname”元素的值。
  2. Alert()变量的内容。

当点击onclick属性所在的元素时,该属性将运行分配给它的javascript。