views:

4530

answers:

7

I am getting data from a database through AJAX and appending tags to a select statement. The following code works in firefox, but only partially in IE. The problem in IE is that is creates the option elements in the dropdown, but the "text" attribute value is empty (the dropdown appears with 30 blank rows! However, the "value" attribute value gets set correctly (which is hte primary key from my database). Is there a different field I need to set in IE other than "text"? The bolded text in teh code below is where I think the problem lies. BTW, value is not empty, and i have tried putting in a string literal in its place and it is still blank in IE.

The code is:

$.each(data, function(key,value){
    $("<option>").attr("value", key).attr("text",value).appendTo("#select1");
});
+5  A: 

I would try to use .text() instead:

  $.each(data, 
       function(key,value){ 
           $("option").attr("value", key)
                .text(value)
                .appendTo("#select1"); 
        });

I think this is what you are going for?

altCognito
Yes, your solution worked exactly in both IE and Firefox! There are many examples on the Internet that use .attr("text", value) which I guess is wrong. Thank you very much for the solution!
Dan
Remember also that .text() automatically escapes any HTML you set within it, i.e. .text("<em>foo</em>") will be set as "<em>foo</em>". If you want to include HTML there, use .html().
cdmckay
A: 

I don't think the posted solution is correct. I believe it should be:

$.each(data, function(key,value){ $("").attr("value", key) .text(value) .appendTo("#select1"); });

not

$.each(data, function(key,value){ $("option").attr("value", key) .text(value) .appendTo("#select1"); });

The <>'s got dropped somehow.

A: 

Lets try that again with block quotes:

The solution should be:

$.each(data, 
       function(key,value){ 
           $("<option>").attr("value", key)
                .text(value)
                .appendTo("#select1"); 
        });

"options" needs to be surrounded with <>

A: 
$.each(data, 
   function(key,value){ 
       $("<option>").attr("value", key)
            .text(value)
            .appendTo("#select1"); 
    });

seem to have worked for me.

Arnold Gamboa
A: 

altCognito is correct... however, if you are looping through integers, be sure that you use

key/value.toString() - while jQuery won't throw any errors and will handle it, it'll avoid additional overhead.

it's all about performance, right? :)

$.each(data,  
       function(key,value){  
           $("option").attr("value", key.toString()) 
                .text(value.toString()) 
                .appendTo("#select1");  
        }); 
Paul Shaver
A: 

This worked for me too. Thanks a lot for your solutions!

binusida