InGeek
InGeek

Reputation: 2682

Delete specific range of elements JQuery

Html:

<select id ="combooptions">
          <option id="combostart" value=""></option>
 </select>

js:

var str = "";
if (combonews.length > 0)
        for (var i in combonews) {
            str += "<option value='" + combonews[i][0] + "'>" + combonews[i][1] + "</option>";
        }
    jQuery("#combooptions").append(str);

It works fine, but now I want to remove those appended one, leaving the initial 1 option tag, as shown above. I tried:

jQuery("#combooptions").html('');
 //or
jQuery("#combooptions").append('');
//or
jQuery("#combostart").append('');
//or
jQuery("#combostart").html('');

but no success.

Please help thank You

Upvotes: 1

Views: 1179

Answers (4)

Matus
Matus

Reputation: 437

Try this:

$('#combooptions').html("<option id='combostart' value=''></option>");

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Since you gave the first option a unique ID, just do:

$('#combostart ~ option').remove();

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Upvotes: 3

Mark Walters
Mark Walters

Reputation: 12390

You could select all options and then remove the one with id combostart from your selection. Then call .remove() to remove the unwanted options.

$('#combooptions option').not('#combostart').remove();

Upvotes: 1

Lekensteyn
Lekensteyn

Reputation: 66415

To shrink a select list, you can also lower the number of options:

document.getElementById("combooptions").length = 1;

With jQuery:

$("#combooptions")[0].length = 1;

More generic idea to remove "all but the first":

$("#combooptions :not(:first-child)").remove();

Example: http://jsfiddle.net/kVRpy/

Upvotes: 3

Related Questions