0

If I have a dropdownlist with two list elements as below then I want to remove the top one. I know this bit of code would remove the element $('#DeliveryOptionId option:nth-child(1)').remove(); but how can we count the items before removing the first.thanks

 <select  id="DeliveryOptionId" name="DeliveryOptionId" class="valid">
    <option value="">Delivery options</option>
    <option value="1">Post article to me</option>
 </select>

4 Answers 4

3

If you want to know the number of items in the select, use length:

var numberOfOptions = $('#DeliveryOptionId option').length;
Sign up to request clarification or add additional context in comments.

Comments

2

Use $('#DeliveryOptionId option').length to check for length and then remove.

if($('#DeliveryOptionId  option').length > 1) {
    $('#DeliveryOptionId option:nth-child(1)').remove();
}

3 Comments

@ComFreek: Thanks mate, clicked the button a tad early :D
You don't even need > 1 ;)
@ComFreek: Correct for that sample it is not needed. But I am not sure when the OP wants to remove the option. If the need is say to delete if there are more than 3 options (or some number like that) then the check for >3 would be needed :)
0

length returns the number of jQuery elements found by the selector

var nr = $('#DeliveryOptionId option').length;

If you want to remove the first option use:

$('#DeliveryOptionId option').first().remove();

or

$('#DeliveryOptionId option:first').remove();

And if you want to remove the last use last() (or :last) instead of first() (or :first).

Comments

0
$("#DeliveryOptionId option").length;

3 Comments

Please don't post the same answer as others have already done, instead, give upvotes to them.
or if you post the same code as someone else at the same time (happens all the time - 2 same answers at once), add some more explanation, example, JSFiddle etc. - that way you make your answer more valuable and possibly the one to be accepted
Okey, thanks for the tips. The other answers were posted while i was typing mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.