Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all values but the first from a drop down list 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 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!

like image 343
Hriskesh Ashokan Avatar asked Jul 15 '11 01:07

Hriskesh Ashokan


People also ask

How remove all options from dropdown in jQuery?

To remove all options from a select list using jQuery, the simplest way is to use the empty() method.

How do I remove the first option in select?

find('option'). get(0). remove(); }); This simply removes the first option of a select tag on click.

How do I remove a selected value from a Dropdownlist?

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.


2 Answers

An easier approach:

$('#ddlPollQuestions').children('option:not(:first)').remove();
like image 79
gsk Avatar answered Nov 10 '22 01:11

gsk


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>');
 }
like image 35
Chandu Avatar answered Nov 10 '22 00:11

Chandu