Home > Mobile >  Is it possible to give a submit input button the onsubmit attribute with javascript?
Is it possible to give a submit input button the onsubmit attribute with javascript?

Time:10-22

Hello I've tried several things to give my submit button the onsubmit attribute. But I can't figure out, how to set onsubmit. Maybe you have an idea.

let btn = document.createElement('input');
            btn.value = "Delete";
            btn.name = "deleteButton";
            btn.type = "submit";
            btn.onsubmit="deleteCell();
let btn = document.createElement('input');
            btn.value = "Delete";
            btn.name = "deleteButton";
            btn.type = "button";
            btn.addEventListener('submit', deleteCell())

CodePudding user response:

The "submit" event is for a form, not an input. You can use the "click" event on the input though:

const deleteCell = () => {
    console.log("hello World!")
};
let btn = document.createElement('input');
btn.value = "Delete";
btn.name = "deleteButton";
btn.type = "button";
btn.addEventListener('click', deleteCell);

CodePudding user response:

A button does not have a onSubmit or submit event.

onSubmit is a property of a <form> element.

With button, you should use btn.onClick = deleteCell or addEventListener('click',deleteCell)

Have a look here for more details on a similar question.

onSubmit event on a button element will it work?

CodePudding user response:

What exactly are you trying to achieve? Usually a submit button is wrapped inside a <form> tag. The form might have a onSubmit attribute or an action and a method. A button can have the onClick attribute to run a specific function.

CodePudding user response:

onsubmit is a property defined on the form element, not a [submit] button. The property is there as equivalent to handling "submit" type of events, which also are dispatched on a form, not button(s).

If you want to know which of the submit buttons was responsible for form submission, there happens to be a "submitter" property on the event that is passed to the onsubmit function you define, or the one that is passed to the event listener (assuming form below is a reference to a "form" element):

form.onsubmit = ev => {
    ev.submitter; /// This is the button that submitted the form.
};
  • Related