It is not necessary to add yet another getElementById() inside the submit form handler function. I am confused as to why this approach is so common. What would you do if you needed to fetch multiple dozens / all values of the form? Write dozens of element selectors?
I think the following is much cleaner:
Inputs can include a name attribute which eases their access:
function submitForm(event) {
event.preventDefault()
alert(event.target.elements.searchTerm.value)
}
<form onsubmit="submitForm(event)">
<input name="searchTerm"/>
<button>Submit</button>
</form>
Even shorter,
function submitForm(that) {
alert(that.searchTerm.value)
}
<form onsubmit="submitForm(this)">
<input name="searchTerm"/>
<button>Submit</button>
</form>
In the handler itself, you can even access values directly:
<form onsubmit="alert(searchTerm)">
<input name="searchTerm"/>
<button>Submit</button>
</form>
Because the handler itself has an implicit with(this) (details).
If you register the event handler via JS, the this (in non-lambda functions) already points to the form element, so you can also do
document.querySelector('#myForm').addEventListener('submit', function() {
event.preventDefault()
alert(this.elements.searchTerm.value)
});
<form id="myForm">
<input name="searchTerm"/>
<button>Submit</button>
</form>
Finally, to transform multiple inputs into a key-value object, you can use Object.fromEntries: (2)
function submitForm(event) {
event.preventDefault()
const obj = Object.fromEntries(new FormData(event.target).entries())
// Prints: { searchTerm: "...", myCheckbox: "on" }
console.log(obj)
return false;
}
<form onsubmit="submitForm(event)">
<input name="searchTerm"/>
<input type="checkbox" name="myCheckbox"/>
<button>Submit</button>
</form>
$("form").submit(function(){ // Do stuff });