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!
To remove all options from a select list using jQuery, the simplest way is to use the empty() method.
find('option'). get(0). remove(); }); This simply removes the first option of a select tag on click.
With jQuery, you can use the . remove() method to takes elements out of the DOM. To get the selected item from a dropdown, you can use the :selected property and call remove() on the matched element.
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>');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With