Reputation: 1945
I would like to populate a select box with data fetched by ajax.
The initial HTML code looks like:
<select id="myid" name="myname">
</select>
I need to avoid innerHTML
and other such workarounds. I tried using appendChild
but it did not seem to work.
I am really new to prototype, so I really dont know how to go about it.
Upvotes: 0
Views: 927
Reputation: 3422
Assuming you wanted to add all members of a self-created object as key-value pairs to a select
element, you could do that this way:
var data = {
a: 'Peter',
b: 'Paul',
c: 'Mary'
};
$('mySelect').update($H(data).map(function(o) {
return '<option value="' + o.key + '">' + o.value + '</option>';
}).join(''));
You find a jsFiddle of it here.
The basic idea behind the code is, that you create your option
elements from the given data object, by transforming every one of them into a string. That is done by the map method.
The $H
will transform the data object into a Prototype Hash
object, which comes in handy here, as it will pass a { key, value }
object to the first parameter of it's map invocation.
After transforming all elements to Strings, you just have to join
them by an empty String (or whatever non-HTML code you like, \n would do as well) to be able to use them for the update
method.
To be honest, Element#update uses innerHTML
so that is actually not a workaround. It's just one way to do it.
Upvotes: 1