Perform function on form submit

2019-07-15 09:53发布

Hopefully this is a pretty simple question! I've got the code working in jQuery to listen for a specific form on a page to be submitted and perform an alert when it is.. I.e.: The form itself doesn't have an ID so I am targeting the form within a specific DIV ID.

$("#content form").submit(function() {
    alert("lorem ipsum dolor?");
});

What would be the syntax for performing this in javascript alone without using jquery? For example, I have this code (below) and just am unsure of how to listen for the form to be submitted to perform an action..

var submitform = document.getElementById("content").getElementsByTagName("form");

Thanks!

4条回答
孤傲高冷的网名
2楼-- · 2019-07-15 09:57

To do it in a cross browser, not destructive way, it takes a bit of code:

var submitform = document.getElementById("content").getElementsByTagName("form")[0],
    callback = function(){
       alert("lorem ipsum dolor?");
    };


if(window.addEventListener){
   submitform.addEventListener("submit", callback, false); // Most modern browsers
} else if (window.attachEvent){
   submitform.attachEvent("onsubmit", callback); // IE
} else {
   submitform.onsubmit = callback; // Destroys other handlers
}
查看更多
Juvenile、少年°
3楼-- · 2019-07-15 10:07

You can use the onsubmit handler.

查看更多
聊天终结者
4楼-- · 2019-07-15 10:09

First of all, you should known that the getElementsByTagName will return a NodeList, you need to get the first DOM element, e.g.:

var submitForm = document.getElementById("content")
                         .getElementsByTagName("form")[0];

Then you can bind the submit event:

submitForm.onsubmit = function () {
  alert("lorem ipsum dolor?");
};
查看更多
男人必须洒脱
5楼-- · 2019-07-15 10:16
submitform.onSubmit = function() {
    alert("lorem ipsum dolor?");
}
查看更多
登录 后发表回答