7

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.

5
  • div tag is as follow <div id = "idcatFill"></div> Commented Nov 17, 2013 at 13:07
  • There is an edit button underneath your question if you feel you need to add something. Commented Nov 17, 2013 at 13:09
  • Please use jsbeautifier.org to format your HTML and JS code. Also could you please create a fiddle? Commented Nov 17, 2013 at 13:11
  • I need to create the tag when the web page is loading.I got the relevent data by the database to data variable.(checked with the alert). Commented Nov 17, 2013 at 13:12
  • A bit slow, but I would do -> jsfiddle.net/een55 Commented Nov 17, 2013 at 13:23

2 Answers 2

6

Simply:

$.each(data, function (index, value) {
  $('#idcatFill').append($('<option/>', { 
      value: index,
      text : value 
  }));
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.