用javascript提交表单后显示消息

时间:2020-04-22 06:29:00

标签: javascript html

在用javascript单击“提交”按钮后,我想显示该消息,键入我要提交的内容。 我想知道我是否必须在JavaScript中使用警报或模式。我只想使用Javascript而不是JQuery或Ajax。

<body>

<form action="index.html" method="POST">
 <label for="FirstName">First Name:</label>
 <input type="text" id="FirstName" placeholder="First Name">
 <label for="LastName">Last Name:</label>
 <input type="text" id="LastName" placeholder="Last Name">
 <input type="Submit" value="Submit" />
</form>

</body>

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

let form = document.getElementsByTagName("form")[0];
form.addEventListener("submit", (e) => {
  e.preventDefault();
  alert("Form Submitted!");
});
<form action="index.html" method="POST">
  <label for="FirstName">First Name:</label>
  <input type="text" id="FirstName" placeholder="First Name" />
  <label for="LastName">Last Name:</label>
  <input type="text" id="LastName" placeholder="Last Name" />
  <input type="Submit" value="Submit" />
</form>

答案 1 :(得分:1)

我希望以下代码会有所帮助。

let form = document.getElementById("form");

form.onsubmit = function(){
let inputs = Object.fromEntries([...form.children].filter(e=>e.localName=="input"&&e.placeholder).map(e=>[e.placeholder,e.value]));

for(key in inputs) alert(key+": "+inputs[key]);
}
<body>

<form id="form" action="index.html" method="POST"> <!--i've added an id -->
 <label for="FirstName">First Name:</label>
 <input type="text" id="FirstName" placeholder="First Name">
 <label for="LastName">Last Name:</label>
 <input type="text" id="LastName" placeholder="Last Name">
 <input type="Submit" value="Submit" />
</form>

</body>