2

Is there any way to Optimize the below lines of code?

        $('#state').children('option:not(:first)').remove();
        $('#city').children('option:not(:first)').remove();
        $('#branch').children('option:not(:first)').remove();
        $('#branchAddress').children('option:not(:first)').remove();

I have tried adding all the fields by comma seperated, but it is not working.

Please help to optimize the above code.

1
  • Are there other selectelements if so plz show the html (or at least the selects) Commented Dec 3, 2012 at 14:25

4 Answers 4

1

I would try something like :

$('#state, #city, #branch, #branchAddress')
    .each(function(i,item){$('option:not(:first)',$(item)).remove();});

or like this :

$('#state, #city, #branch, #branchAddress').find('option:not(:first)').remove();

at last (but I wouldn't call it optimization ;-)

$('#state option:not(:first), #city option:not(:first), #branch option:not(:first), #branchAddress option:not(:first)').remove();
Sign up to request clarification or add additional context in comments.

3 Comments

You're right about the not-working-children/working-find methods... I'll try to find out why.
@sp00m and $('#state,#city,#branch,#branchAddress').children('option:not(:first-child)').remove(); seems to be working...
Haha, awesome, here is mine: http://stackoverflow.com/q/13686415/1225328. I guess we came across the same answer ;)
0

Try

$('#branchAddress #state #city #branchAddress').children('option:not(:first)').remove();

Its possible to have multple elements in the selector.

Comments

0

add the same class to all of the above and refer to it once instead of referring to the ID's multiple times

Comments

0

The following should do (see also jQuery multiple-selector api)

$('#state, #city, #branch, #branchAddress').children('option:not(:first)').remove();

Comments

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.