views:

69

answers:

6

i use jquery ajax to get data from 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 doesnt work. Weird. how can i solve this?

+3  A: 

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.

Chris C
i have tried that it doesnt work?
never_had_a_name
what is the difference between text() and innerhtml()?
never_had_a_name
http://docs.jquery.com/Manipulation
Chris C
i have updated the question so your answer wasn't correct anymore. so i unchecked it:)
never_had_a_name
@fayer: i updated my response to answer the updated question
Chris C
A: 

The accepted answer to this question shows you how to append options to selects using jQuery, rather than replacing existing ones.

Peter Hansen
A: 

check out the jQuery docs append function

PetersenDidIt
+1  A: 

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.

DisgruntledGoat
+2  A: 

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>
brianpeiris
A: 

i used jquery remove function to remove all siblings to the first option before i appended new options...it worked great...=)

never_had_a_name