【问题标题】:Display message after form submit with javascript使用javascript提交表单后显示消息
【发布时间】:2020-04-22 06:29:00
【问题描述】:

我想在点击提交按钮后用 javascript 显示我输入的提交信息。 我想知道我必须使用 javascript 来使用 alert 或 modal 。我只想使用 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>

【问题讨论】:

  • 你已经尝试了什么?

标签: javascript html


【解决方案1】:

您可以执行以下操作:

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>

【讨论】:

    【解决方案2】:

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

    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>

    【讨论】: