JQuery 创建一个表单并以编程方式向其中添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4497140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:21:42  来源:igfitidea点击:

JQuery create a form and add elements to it programmatically

jquery

提问by EBAG

Hi I need to create a form and add elements to it programatically.

嗨,我需要创建一个表单并以编程方式向其中添加元素。

$form = $("<form></form>");
$form.append("<input type=button value=button");

this doesn't seem to work right.

这似乎不起作用。

回答by Sarfraz

You need to append formitself to bodytoo:

您也需要将form其附加到body

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);

回答by Arvin

The 2nd line should be written as:

第 2 行应写为:

$form.append('<input type="button" value="button">');

回答by Sergio Viera

var form = $("<form/>", 
                 { action:'/myaction' }
            );
form.append( 
    $("<input>", 
         { type:'text', 
           placeholder:'Keywords', 
           name:'keyword', 
           style:'width:65%' }
     )
);

form.append( 
     $("<input>", 
          { type:'submit', 
            value:'Search', 
            style:'width:30%' }
       )
);

$("#someDivId").append(form);

回答by manoj Bhambere

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

回答by Shurdoof

The tag is not closed:

标签未关闭:

$form.append("<input type=button value=button");

Should be:

应该:

$form.append('<input type="button" value="button">');