Skip to content
Advertisement

JQuery update select option

Need a little help on this one. I am trying to write jQuery code to change the selection of a select dropdown. Following the excellent advice on here, I am using .val(). However, this doesn’t remove the selected attribute, so I am also doing that.

The part where I am stuck is, I want to add the selected attribute to the new option, but the value of the new option (which is stored in the PHP value $option) has double quotation marks in it.

JavaScript

Thanks!

Advertisement

Answer

AFAICT you are just trying to select one of the options in your select. You need to use .prop() to do that reliably. There is a note about this in the docs. They are writing about the checked attribute, but a note below says the same applies to selected:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does …. The same is true for other dynamic attributes, such as selected and value.

So once we are using the right method, the only problem to worry about is that pesky quote. We can solve that by carefully arranging double and single quotes.

Working (simplified) JSFidddle

HTML

JavaScript

Javascript

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