使用jQuery即时创建标签

时间:2012-05-01 16:41:48

标签: jquery forms jquery-ui jquery-ui-datepicker dom-manipulation

我需要动态创建标签和文本字段,还包括文本字段的日期选择器。我需要这样的东西:

<label for="from">From </label> <input type="text" id="from" name="from" />

我在jQuery中尝试过类似的东西:

var label = $("<label>").attr('for', "from");   
                    label.html('Date: ' +
                        '<input type="text" id="from name="from" value="">');

                    $(function() {
                        $("#from").datepicker();
                    }); 

这个不知何故不会创建标签和文本字段。我不确定我错过了什么。

修改

更确切地说,我在portlet中使用它,并且我在jsp页面中没有body标签。所以当我调用函数追加到body时它就不会。

4 个答案:

答案 0 :(得分:25)

这样的事情会起作用:

//Create the label element
var $label = $("<label>").text('Date:');
//Create the input element
var $input = $('<input type="text">').attr({id: 'from', name: 'from'});

//Insert the input into the label
$input.appendTo($label);
//Insert the label into the DOM - replace body with the required position
$('body').append($label);

//applying datepicker on input
input.datepicker();

jsFiddle Demo

请注意,如果输入元素位于标签内,则不必使用标签上的for属性。所以使用其中一个:

<label><input id="x1"></label>

<label for="x1"></label> <input id="x1">

答案 1 :(得分:4)

您需要将您创建的标签附加到DOM才能显示:

var label = $("<label>").attr('for', "from");
    label.html('Date: ' +
      '<input type="text" id="from name="from" value="">');

label.appendTo('body');

// set up datepicker
label.find('#from').datepicker();

答案 2 :(得分:1)

您想在哪里插入标签?如果你想在页面的开头,你可以做这样的事情。

var $label = $("<label>").attr('for', "from");   

$label.html('Date: <input type="text" id="from" name="from" value="">');

$(function() {
    $('body').prepend($label);

    $(':input', $label).datepicker();
});

答案 3 :(得分:0)

1)您在ID属性的末尾缺少结束引号 2)您没有将标签贴在任何东西上。

相关问题