简体   繁体   中英

Display message after form submit with javascript

I'd like to show the message what I type for submitting after clicking submit button with javascript. I wonder I have to use alert or modal for it with javascript. I just want to use Javascript instead of JQuery or 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>

You could do something like the following:

 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>

I hope the following code will help.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM