OOP中的动态表单创建和提交

Dynamic Form Creation and submission in OOP

本文关键字:创建 提交 表单 动态 OOP      更新时间:2023-09-26

我正在尝试创建一个类来动态创建表单,然后提交表单。这是一个简单的类,但现在我迷失了方向。

       var creathtml=function(){
       this.createform=function(o,title){
        var openingtag="<form action='#' class='form-horizontal well' onSubmit='this.submitform'><fieldset><legend>"+title+"</legend>";
        var fields="";
        for (var i=0; i<o.length; i++)
        {
            if(o[i].type=='input')
            {
            fields+="<div class='control-group'><label class='control-label' for='"+o[i].id+"'>"+o[i].label+"</label><div class='controls'><input type='"+o[i].subtype+"'  id='"+o[i].id+"' class='"+o[i].class+"'></div></div>";
            }
            if(o[i].type=='button')
            {
            fields+="<div class='control-group'><div class='controls'><button type='"+o[i].subtype+"'  id='"+o[i].id+"' class='"+o[i].class+"'>"+title+"</button></div></div>";
            }

        }
        var closingtag="</fieldset></form>";
            $(body).html (openingtag+fields+closingtag;
        };
    this.submitform=function()
        {
         console.log('mnmnmnmn');
                     return false;          
        }   
    }

用法

            var obj= new creathtml;
                var  h=obj.createform([
             {'type':'input','subtype':'input','name':'Wow','label':'Item Name','id':'itmname','class':''},
             {'type':'input','subtype':'input','name':'hello','label':'Item Code','id':'hello','class':''},
             {'type':'input','subtype':'input','name':'hello','label':'Item Code','id':'hello2','class':''}, 
         {'type':'button','subtype':'submit','name':'submit','label':'Null','id':'submit','class':'btn btn-primary'}
             ],'Create New Items');

我已经成功地创建了HTML并在DOM上进行了填充。但不知道如何检测表单提交或为这个特定类创建提交方法?

这是我第一次尝试javascript OOP,所以如果做得不对,请尽可能建议正确的方法

您已经检测到使用onSubmit='this.submitform'提交的表单。此外,如果可能的话,您可能希望使用模板引擎。

由于您已经在使用jQuery,因此为表单提交添加一个监听器将是理想的选择:

this.createform = function(o,title) {
    ...
    for (var i=0; i<o.length; i++)
    {
        ...
        $('.' + o[i].formClass).on('submit', function() {
            console.log('handle form submit here');
        });
    }
...
};