msg
msg

Reputation: 1540

how to assign array values into dynamically created textboxes using jquery?

i have created a list of textboxes through for loop using Jquery Mobile. I need to populate text to these textboxes from an array list. i have tried using following code, which was not working properly.

var myArray = ["Lion","Tiger","Deer","Elephant","Zebra"];
<div class="ui-grid-a"></div>

script tag contains;

for(i=0;i<5;i++)
{
var content = '<div class="ui-block-a">'
content += '<input data-role="none" type="text" id="textboxId" readonly/>'
$('#textboxId').val(myArray[i]);
content += '</div>'
$('.ui-grid-a').append(content);
}

Upvotes: 3

Views: 7710

Answers (4)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could do:

var myArray = ["Lion","Tiger","Deer","Elephant","Zebra"];
for(i=0; i < myArray.length; i++) {      
      $("<div />", {
          "class" : "ui-block-a"
      }).append($("<input />", {
          "data-role": "none",
          "value": myArray[i],
          "type" :"text",
          "readonly": true
      })).appendTo(".ui-grid-a");
}

Demo:: jsFiddle

Upvotes: 1

Somnath Kharat
Somnath Kharat

Reputation: 3600

var myArray = ["Lion","Tiger","Deer","Elephant","Zebra"];
<div class="ui-grid-a"></div> 

Your Script:

        for(i=0;i<5;i++)
        {
           var content = '<div class="ui-block-a">'
           content += '<input id="textboxId '+i+'" readonly value="' + myArray[i] + '"data-role="none   "type="text" />'
           $('.ui-grid-a').append(content);
        }

Upvotes: 1

Yasitha
Yasitha

Reputation: 2303

You need to have different ids for each divs.

var myArray = ["Lion","Tiger","Deer","Elephant","Zebra"];

for(i=0;i<5;i++)
{
    var content = '<div class="ui-block-a">'
    content += '<input data-role="none" type="text" id="textboxId_'+i+'" readonly/>'
    content += '</div>'
    $('.ui-grid-a').append(content);
    $('#textboxId_'+i).val(myArray[i]);
}

Demo

Upvotes: 4

Adil
Adil

Reputation: 148110

You are trying to access an element that is not yet added to DOM, you can add value to textbox that time you adding it in content string. Note you are using same id for all textboxes that is also wrong. You can append i to id of textbox to make id unique.

content += '<input id="textboxId"'+i+'" readonly value="' + myArray[i] + '" data-role="none" type="text" />'

Upvotes: 4

Related Questions