Edit an option of a select menu using jQuery

How to edit an individual option of a select menu using jQuery

I have read many articles that cover how to use jQuery to add and remove options from a select box but I couldn’t find one that covered how to edit an individual option.

I knew there had to be a way and the good people of Stack Overflow were able to answer my question.

Use the option selector in order to grab the element you want

$('#selectID option[value="knownValue"]').text('New Option Text');

So what we are saying here is for every element with the ID of ‘selectID’ look for an option with the value of ‘knownValue’.

Change the text of that option to ‘New Option Text’.

A use case for this (and indeed the reason why I was looking it up) is that if you have a collection of objects and you want to edit them dynamically by selecting them via dropdown then edit the fields you will most likely want to edit the ‘name’ field or some other field that represents the unique name which appears in the dropdown list.

If this is the case when you edit your name and hit save, assuming it is all done using ajax the value in the dropdown will no longer equate to the value stored in the database. This is a usability concern so you should use the method above to ensure that the option text of the dropdown gets edited accordingly.

Recent posts View all

Web DevMarketing

Getting more out of Plausible

Some things we've done to up our Plausible analytics game

Web Dev

Creating draft posts in Jekyll

How to create and develop with draft posts in Jekyll