java begineer
java begineer

Reputation: 319

How to create an HTML Input dynamically using jQuery?

I want to create below html inputs dynamically using jQuery inside the form. Is this possible using jQuery?

<div class="form-group">
  <label class="col-sm-2 control-label">Enter Name</label>
  <div class="col-sm-10">
    <input type="text" class="form-control" id="nameId" name="fullNme" placeholder="Enter full Name">
  </div>
</div>

I want to place the above dynamic div and texbox under div class="box-body"

<form id="myform" class="form-horizontal" method="post">
  <div class="box-body">


  </div>
</form>

Can someone help how can I achieve in Jquery/Javascript?

Appreciate your help in advance!

Upvotes: 3

Views: 7260

Answers (2)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You can do,

var formgroup = $("<div/>", {
  class: "form-group"
});
formgroup.append($("<label>", {
  class: "col-sm-2 control-label",
  text: "Enter Name"
}));
var colsm = $("<div/>", {
  class: "col-sm-10"
});
var input = $("<input/>", {
  type: "text",
  class: "form-control",
  id: "nameId",
  placeholder: "Enter Full Namee"
});
colsm.append(input);
formgroup.append(colsm);
$(".box-body").append(formgroup);

Fiddle

You can give any number of attributes like this.

Upvotes: 3

Aju John
Aju John

Reputation: 2234

You can do like this:

<script>
    var html = '<div class="form-group"><label  class="col-sm-2 control-label">Enter Name</label><div class="col-sm-10"><input type="text" class="form-control" id="nameId" name="fullNme" placeholder="Enter full Name"></div></div>';

    $('.box-body').html(html);
</script>

Another way is:

<div id="container-bkp" style="display:none">
<div class="form-group">
  <label class="col-sm-2 control-label">Enter Name</label>
  <div class="col-sm-10">
    <input type="text" class="form-control" id="nameId" name="fullNme" placeholder="Enter full Name">
  </div>
</div>
</div>

<script>
    $('.box-body').html($('#container-bkp').html());
</script>

Upvotes: 1

Related Questions