sourabh
sourabh

Reputation: 152

how to add a value on input field when appending it to DOM using jquery

I want to add a value to the input field when it is append to DOM.

var strarray = [ "web developer", "web designer" ];
for (i = 0; i <= strarray.length-1; i++) {
    j = [{ 'emp': strarray[i] }];
    var a = j[0]['emp'];
    console.log(a);
    $("<input type='text' value=" + a + "/>")
        .attr("id", "myfieldid"+i)
        .attr("name", "myfieldid[]")
        .appendTo(".mycal");
}

Upvotes: 8

Views: 143

Answers (2)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You can use

var input = $("<input/>", {
    "type": 'text',
    'value': a,
    'id': "myfieldid" + i,
    'name': "myfieldid[]"
});

$(".mycal").append(input);

Fiddle

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can create element using jQuery

var strarray = ["web developer", "web designer"];
for (i = 0; i <= strarray.length - 1; i++) {
  j = [{
    'emp': strarray[i]
  }];
  var a = j[0]['emp'];
  console.log(a);
  $("<input>", {
      'type': 'text',
      'value': a,
      'id': "myfieldid" + i,
      'name': "myfieldid[]"
    }).appendTo(".mycal");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class=mycal></div>

Upvotes: 2

Related Questions