I've found the caching performed in the val() function troublesome in my last project.
First of all, allow me to explain what I'm trying to do.
I need to dynamically hide and show some options inside a select. The naive approach, trying to hide the option elements themselves, only worked in desktop browsers. For mobile browsers, this is not the case: they render all elements (even the hidden ones).
The only way of hiding options dynamically in Android I've found is wrapping the options to be hidden in a span with visibility none. I know its a hack and shouldn't be done, but I have a valid use case: The select has a large list of options that need to be filtered according to an input field, and performing a query over the SQLite DB and then repopulating the select is slow and complicated in code. This hack allows me to load the big list once, then dynamically hide and show options as the user types some filters.
I've created a JSFiddle showing the problem here:
I've read the source code for the `val` function and found that values are first searched in a `valHooks` array, and only if not found there the actual element.value is returned. After applying the hack, it returns the old (wrong) value, despite the field is now showing the second option and the inner HTML element has the second option marked as selected.
After the user manually changes selection, the problem persists.
I'd expect the `val` function to reflect the state of the actual HTML select element, but instead wrong values are returned.