I have a form I am trying to submit with HTML and JavaScript. I have attached an event listener to my checkboxes (.checkbox), that waits for a click, and upon a click, launches a function that attempts to submit the form.
I have succeeded with jQuery's .parent() usage, but am now attempting to switch that to vanilla JS.
I have tried this.parentNode.submit();, however it gives back the error message.
this.parentNode.submit is not a function at HTMLInputElement.formSubmit
Is there a possible way I can submit my form by replacing the jQuery $(this).parent().submit() to a vanilla JS equivalent?
HTML:
<form id="theform" action="/phones/search_results" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓">
<label>
<input type="checkbox" name="brand_name" id="brand_name" value="Apple" class="Apple brand checkbox" style="height: 30px;">
Apple
</label>
$(function() {
var checkbox = document.querySelectorAll(".checkbox");
for (var i = 0; i < checkbox.length; i++) {
checkbox[i].addEventListener("click", formSubmit)
}
});
function formSubmit(){
if(this.checked){
$(this).parent().submit();
console.log("Form was submitted" + this.parentNode)
}
}
You could use the parentNode property, but in your case that will point to the label element, so it would become event.target.parentNode.parentNode. It is probably easier to use the even target form property, like this.
function formSubmit(event){
event.target.form.submit();
this.parentNode.parentNode.submit(); //Alternatively without event, using parentNode
}
document.getElementById("brand_name").onclick=formSubmit;
You can select the enclosing form element and submit it as such:
element.closest( 'form' ).submit();
This ignores any nesting and doesn't require you to loop through the form yourself. It functions like querySelector in that it can also return null, so beware of that as it will throw an error if it's not nested in a form.
MDN https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
You can trigger a submit event from a child element that will be catched by an enclosing form element like this:
const event = new Event('submit', {bubbles: true, cancelable: true});
childElement.dispatchEvent(event);