Reputation: 2685
I have a url which returns a bunch of options tags. Can I stick that in my $.ajax success:
function(html) {
}
Can I push all the option tags directly inside my select tag after emptying my select tag.
my select tag has a name of "SelectName".
I was thinking something like so:
$("select[name='selectName']").appendTo($(html)); // but this doesn't work
my html looks like this (its nothing but option tags and it comes from a url options.apsx:
<option id="1">test1</option><option id="2">test2</option>...
Upvotes: 0
Views: 1733
Reputation: 45
Solution Proposed: Pure JavaScript AJAX Solution
//HTML
<select id="category">
<option value="0">--Please Select Category--</option>
</select>
//Javascript onload Event
<script>
window.onload = function(){
var cat = document.getElementById('category');
loadCat(cat);
};
//Function that will assign Category to Element
function loadCat(element)
var e = element;
var xhr = new XMLHttpRequest();
var url = 'load_categories.php';
xhr.open('GET',url, true);
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
var r = JSON.parse(xhr.responseText);
for (var key in r) {
if (r.hasOwnProperty(key)) {
var tempNode = document.createElement("option");
tempNode.value = r[key];
var textnode = document.createTextNode(r[key]);
tempNode.appendChild(textnode);
e.appendChild(tempNode);
}
}
}
};
xhr.send();
}
</script>
Server must return a basic JSON Object. The above example will work with the server JSON Response:
//JSON RESPONSE FROM SERVER
{"1":"Module","2":"Essential","3":"Security","4":"Improvement"}
Node Credit goes to the link below:
https://www.w3schools.com/jsref/met_node_appendchild.asp
Upvotes: 0
Reputation: 253416
You could put something like this into your success function:
$("select[name='selectName']").empty();
$(html).appendTo("select[name='selectName']");
Assuming that html
is the set of option
tags returned by the function.
Upvotes: 1
Reputation: 40863
I am guessing you are looking for append()
$("select[name='selectName']").append(html);
Using appendTo
is trying to append the select list to your <options/>
which is backwards to what you want to happen.
Example on jsfiddle.
Upvotes: 2