I use jquery ajax to get data from the PHP file.
data = <option>Peter</option><option>Maria</option>
I want to then use jquery to put this data after the first option
<select>
<option>Name</option>
</select>
I cant use html() on select because then the first option will be deleted. what jquery function can I use to put them after the first one?
EDIT: i cannot use append because then when i make another request and the data is:
data = <option>Michael</option><option>Erik</option>
Peter and Maria will still be in the Select list. how can I do? I have tried to have a
<div id=addhere></div>
after the first option and then use html() but it doesn't work. We开发者_StackOverflow社区ird. how can I solve this?
Save the original options in a variable and append the AJAX response along with the original options.
Working demo:
http://jsbin.com/otiro (editable via http://jsbin.com/otiro/edit)
Source:
<select id="name">
<option>Name</option>
</select>
<script type="text/javascript">
var nameSelect = $('#name'), originalOptions = nameSelect.children();
function handleAjaxResponse(response) {
nameSelect.children().remove().end().append(originalOptions.add(response));
}
$.get("getNames.php", handleAjaxResponse);
</script>
EDIT: Changing my response to answer your question after you've updated it...
So lets say you return the following via AJAX:
data = "<option>Michael</option><option>Erik</option>";
Then, you can merely update that data, and use html()
data = "<option>Name</option>" + data;
$("#selectToModify").html(data);
Here is the old answer, just for your reference:
$("#divToAddTo").append(data);
html() will replace the innerHTML of an element. append() will append whatever data to the end of the innerHTML.
I'm not sure I fully understand the question, but take a look at the jQuery reference for the functions you can use to insert content. insertAfter
may be the one you're looking for.
check out the jQuery docs append function
i used jquery remove function to remove all siblings to the first option before i appended new options...it worked great...=)
精彩评论