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

时间:2010-12-21 07:39:20

标签: jquery

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

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

这似乎不正常。

6 个答案:

答案 0 :(得分:38)

您还需要将form自身附加到body

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

答案 1 :(得分:23)

第二行应写为:

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

答案 2 :(得分:21)

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);

答案 3 :(得分:5)

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";
    });

}     

答案 4 :(得分:3)

标签未关闭:

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

应该是:

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

答案 5 :(得分:0)

使用 Jquery

不是创建临时变量,而是可以按如下方式以连续流模式编写:

$('</form>', { action: url, method: 'POST' }).append(
    $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
    $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();