简体   繁体   中英

Intercept a dynamic added form submission

Normal form submission intercept can be found. But, my class is different. The form is dynamically added after calling a function. Then, the form submission cannot be captured.

How to capture the form submission like this? Better to use Jquery but altering the dynamic added form attributes is acceptable.

The following is the example. Here is how I capture the form submission.

$(function() {
    $(".formClass").submit(function(e) {
      e.preventDefault();
      var actionurl = e.currentTarget.action;
      alert(actionurl);
    });
});

Here is how forms are added after calling the function - eObj.getFormElement()

(function($){
    function(eObj) {
        var selector = "#abc";

        //Call the function to get the form elements
        eObj.getFormElement(langObj, function(err, x) {
            var elem = "<ul>";
            for (var i=0; i<x.length; i++) {
                 var formId = elementId + "_sform_" + i;
                 elem = elem + "<li class='product_" + i + "'>" 
                 for (var key in x[i]) {
                      elem = elem + "<div class='price'>" + curMap[curKey] + x[i][key].price + "</div>";
                      elem = elem + "<div class='s'><form id='" + formId +"' class='formClass' method='post' action='" + x[i][key].url + "'>"
                           + "<input class='s_btn' type='submit' value='" + submitLabel + "'>"
                           + "</form></div>";
                 }
                 elem = elem + "</li>";
            }
            elem = elem + "</ul>";

        //Append the form to the div after we create the forms 
        $(selector).append(elem);
    }); 
}})(jQuery);

Since You can't set events for non-existing elements You need to set events for element existing.

In this case you can use document to get the event.

http://jsfiddle.net/h189o3xc/

here is a sample code.

$(document).on("submit",function(e){
    if($(e.target).hasClass("formClass")){
        e.preventDefault();
        console.log("you can catch the event!");
        //and do whatever you want.
    }
});

set a event for document and whenever any submit event happens, check whether it's your target form or not. then do whatever you want if it's your target form.

EDITED as @charlietfl mentioned,You can use extra on function's parameter instead of if statement.

the code would be something like..

$(document).on("submit",".formClass",function(e){
      e.preventDefault();
      console.log("you can catch the event!");
      //and do whatever you want.
}); 

http://jsfiddle.net/h189o3xc/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM