Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery create select tag with data from array

I need to access database and update options of a select tag. My code is here.

 $(window).load(function () {

     $.getJSON('http://localhost/ABC/web/app_dev.php/doctorFillOption', function (data) {

         var length = data.length,
             element = null;
         $('#idcatFill').append('<select id ="idCat"  style="width:200px;margin-left:30px;margin-top:5px;" type="text"><option value=""></option>');

         for (var i = 0; i < length; i++) {
             row = data[i];
             alert("id" + row['id'] + ' ' + row['category_name']);
             $('#idcatFill').append(
                 '<option value="' + row['id'] + '">' + row['category_name'] + '</option>'
             );
         }

     });
     $('#idcatFill').append('</select><br/>');
 });

But it doesn't get options. Need help. Thanks.

like image 676
Lakmal Vithanage Avatar asked Nov 17 '13 13:11

Lakmal Vithanage


2 Answers

Simply:

$.each(data, function (index, value) {
  $('#idcatFill').append($('<option/>', { 
      value: index,
      text : value 
  }));
});
like image 56
takeit Avatar answered Nov 07 '22 12:11

takeit


Use the following code to append your tag:

$("#idcatFill").append(function() {
    var elem = $('<select id ="idCat"  style="width:200px;margin-left:30px;margin-top:5px;">');
    for (var i = 0; i < length; i++) {
         row = data[i];
         elem.append('<option value="' + row['id'] + '">' + row['category_name'] + '</option>');
    }
    return elem;
});

you can't attach incomplete elements to the dom. You need to build your <select> tag before inserting it.

like image 1
Chandranshu Avatar answered Nov 07 '22 10:11

Chandranshu