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

EBA*_*BAG 25 jquery

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

$form = $("<form></form>");
$form.append("<input type=button value=button");
Run Code Online (Sandbox Code Playgroud)

这似乎不正常.

Sar*_*raz 42

你也需要追随form自己body:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);
Run Code Online (Sandbox Code Playgroud)


Arv*_*vin 24

第二行应写为:

$form.append('<input type="button" value="button">');
Run Code Online (Sandbox Code Playgroud)

  • 不,不应该......正确使用报价!`.append('<input type ="button"value ="button"/>');` (10认同)

小智 23

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);
Run Code Online (Sandbox Code Playgroud)

  • @decebal - `这看起来像javascript` - 基于JavaScript的jQuery库.它正在构建html标记,然后将其注入到动态的html文档中.这就是OP的重点 - 尽可能在jQuery中做. (2认同)

小智 5

标签未关闭:

$form.append("<input type=button value=button");
Run Code Online (Sandbox Code Playgroud)

应该:

$form.append('<input type="button" value="button">');
Run Code Online (Sandbox Code Playgroud)


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

}     
Run Code Online (Sandbox Code Playgroud)