Skip to content
Advertisement

How select the previous option with jQuery?

I have a html page with a select element like this:

JavaScript

And I’m using this simple function on the button OnClick to change the selected item to the next option item of the dropdown:

JavaScript

My question is: How can i change the selected item to the previous option of this tag using Vanilla JavaScript or jQuery?

Jsbin Example: https://jsbin.com/nuyeduf/edit?html,js,output

Advertisement

Answer

Two problems – first by using attr you’re setting more than one option to selected, which is probably not what you want to do as it will stop the prev() from working as you expect.

Change your code like this:

JavaScript

https://jsbin.com/xewopobasi/1/edit?html,js,output

If you’re using jQuery then stop using onclick attributes and instead assign click handlers appropriately

JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement