Removing all values, but first from dropdown using jQuery
if (questions[0]) { $("select[id$=ddlPollQuestions] > option").remove(); $('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>'); $.each(questions, function(i, question) { $('#ddlPollQuestions').append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>'); }); } else { $("select[id$=ddlPollQuestions] > option").remove(); $('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>'); } What does this mean, it deletes all previous values, but I want my first option, which is “Select a question ...”, to stay and then display “No questions ...” as my second option, My code here doesn’t show “Select Question ..” as the first option. Thanks for watching!
Use : gt selector.
Try this (note that I added a string variable to add parameters after each loop for better performance):
if (questions[0]) { $("select[id$=ddlPollQuestions] > option:gt(0)").remove(); $('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>'); var options = ""; $.each(questions, function(i, question) { options += '<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>'; }); $('#ddlPollQuestions').append(options); } else { $("select[id$=ddlPollQuestions] > option:gt(0)").remove(); $('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>'); } since you delete all parameters in your code, you can simply add Choose a question... again Choose a question... to your else
if (questions[0]) { $("select[id$=ddlPollQuestions] > option").remove(); $('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>'); $.each(questions, function(i, question) { $('#ddlPollQuestions').append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>'); }); } else { $("select[id$=ddlPollQuestions] > option").remove(); $('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>'); $('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>'); } example: http://jsfiddle.net/xeYwv/2/
var $PollQuestions = $('#ddlPollQuestions'); if (questions[0]) { $PollQuestions.children().remove(); $PollQuestions.append('<option value="0">Choose a question to compare to</option>'); $.each(questions, function(i, question) { $PollQuestions.append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>'); }); } else { $PollQuestions.children().remove(); $PollQuestions.append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>'); } what you had is already pretty close.