The form submit is not getting invoked with below code, can someone please help on identifying the problem in the code. Thanks in advance.
<html>
<body>
<form id="form" name="form">
<select name='lstToggleDetails' id='lstToggleDetails' onchange="changeDetailMode1()">
<option value="default">Default</option>
<option value="details">Details</option>
</select>
<input type="submit" value="Register" style="display: none;" >
</form>
<!--Javascript-->
<script>
function changeDetailMode1()
{
var form = document.getElementById('form')
form.addEventListener('submit',function(event){
event.preventDefault()
console.log("in submit");
})
if (document.getElementById("lstToggleDetails").value == "details")
{
console.log("submitting form");
const form1 = document.getElementById("form");
form1.submit();
}
}
</script>
</body>
</html>
CodePudding user response:
This method is similar, but not identical to, activating a form's submit . When invoking this method directly, however:
No submit event is raised. In particular, the form's onsubmit event handler is not run. Constraint validation is not triggered.
Without a submit
event, anything attached via form.addEventListener('submit'
won't run.
Use .requestSubmit
instead, which can be canceled.
You should also probably add the submit handler unconditionally, rather than every time the <select>
changes.
const form = document.getElementById('form')
form.addEventListener('submit', function(event) {
event.preventDefault()
console.log("in submit");
})
function changeDetailMode1() {
if (document.getElementById("lstToggleDetails").value === "details") {
console.log("submitting form");
form.requestSubmit();
}
}
<form id="form" name="form">
<select name='lstToggleDetails' id='lstToggleDetails' onchange="changeDetailMode1()">
<option value="default">Default</option>
<option value="details">Details</option>
</select>
<input type="submit" value="Register" style="display: none;">
</form>