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 this does is it removes all the previous values, But i want my first option, which is "Choose a question ..." to remain, and then display "There are not questions..." as my 2nd option. My code here does not show "Choose a question.." as the first option. Thanks for having a look!
An easier approach:
$('#ddlPollQuestions').children('option:not(:first)').remove();
Use :gt selector.
Try this(Note that I have added a string variable to append the options after the 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 are removing all the options in your code, you'll might just want to append again the Choose a question...
in your else
statement
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.
精彩评论