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>
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>
Share
Improve this question
asked Apr 22, 2020 at 6:29
SooSoo
3972 gold badges10 silver badges19 bronze badges
1
- 1 What have you already tried? – BenM Commented Apr 22, 2020 at 6:30
2 Answers
Reset to default 3You 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>