Get child from children jquery

时间:2015-07-08 15:57:46

标签: javascript jquery html

I need to create the following form dynamically using jquery.

<form>
        <div class="col-xs-12">
            <div class="col-xs-3">
               <label for="startTime">Start Time</label>
                <input id="startTime" name="startTime" style="margin-bottom: 10px" class="form-control" type="text">
             </div>
             <div class="col-xs-3">
                <label for="endTime">End Time</label>
                <input id="endTime" name="endTime" style="margin-bottom: 10px" class="form-control" type="text">
              </div>
      </div>
</form>

This is how I tried it.

 $('#addBodyContainer').append('<form id = "addDataForm" ></form>');
      var form = $('#addBodyContainer').children();
      form.append('<div class = "col-xs-12" ></div>');

var col12Time = form.children();
col12Time.append('<div class = "col-xs-3" ></div>');
var col3StartTime = col12Time.children();
col3StartTime.append(
      "<label for=\"startTime\">"+head[0]+"</label>" +
      "<input id=\"startTime\" name=\"startTime\" style=\"margin-bottom: 10px\" class=\"form-control\" type=\"text\" />"
            );
var col12Time2 = form.children();
col12Time.append('<div class = "col-xs-3" ></div>');
var col3EndTime = col12Time.children();
col3EndTime.append(
       "<label for=\"endTime\">"+head[1]+"</label>" +
       "<input id=\"endTime\" name=\"endTime\" style=\"margin-bottom: 10px\" class=\"form-control\" type=\"text\">"
            );

When I'm creating the end time field. It appears twice in the form. I think the problem occurs with I call form.children() twice. How can I solve this issue?

2 个答案:

答案 0 :(得分:0)

您要将其附加到所有孩子,您需要选择最后一个。

var col12Time = form.children().last();

答案 1 :(得分:0)

您可以像这样创建

var container = $('#addBodyContainer');
var tmp='<form>'+
    '<div class="col-xs-12">'+
    '<div class="col-xs-3">'+
    '<label for="startTime">Start Time</label>'+
    '<input id="startTime" name="startTime" style="margin-bottom: 10px" class="form-control" type="text"/>'+
    '</div>'+
    '<div class="col-xs-3">'+
    '<label for="endTime">End Time</label>'+
    '<input id="endTime" name="endTime" style="margin-bottom: 10px" class="form-control" type="text"/>'+
    '</div>'+
    '</div>'+
    '</form>';
container.append(tmp);