首页 > 解决方案 > 弹出警报用户在文本框中写的内容

问题描述

我的大学有一个练习,我被困住了。我想创建一个页面,通过按“搜索”按钮将显示一个弹出窗口(警报),其中包含“学生 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>

标签: javascripthtmlpopupalert

解决方案


编辑您的 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。


推荐阅读