shoestring
shoestring copied to clipboard
Using .val on select element with multiple
Hi there,
I ran into an issue today with a select
element with a multiple
attribute set, and then trying to call .val()
on it.
Here's an example of jQuery's handling of the same functionality: JS Bin And from their docs:
In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.
I undertand y'all aren't aiming for feature parity, so instead of opening a PR with a fix, I've just written a little failing test case in a fork as an example: 9ee266b22faaa85e1bdb4d024d9875035bb24f40
Is this something you'd like me to fix up, or are you happy not to have this functionality as part of shoestring?
Hey @DylanFM,
If the fix doesn't add a lot of code I think we'd be happy to accept it. Thanks for asking.
It's interesting that getting the value with plain JS returns a string "1"
(example: http://jsbin.com/vuwezogewu/1/edit?js,console )
Is that a common issue in browsers or what's up there?
Anyway, the test and fix would be great to see!
Cool, I'll see what I can come up with tomorrow.
That is an odd find re. the plain-JS .value
. .selectedOptions
seems like it could be useful here, but browser support may be patchy.
I think the plain JS thing comes from this: getValue
The current form control value (i.e. the value of the currently selected option), if multiple options are selected this is the value of the first selected option.
I've written a little fix for shoestring here: 9a0982994454ba7d3345749cd85c02b9ab54f05d
A couple of thoughts:
- This entire method is getting long. It seems like it could be split into 2 internally: 1 for writing and 1 for reading. This could help address the next point, but it's going to result in a little bit more code.
- I've added a few variable declarations to the top of the function, and they conflict with the ones in the loop below (for handling writing to selects). I see this as a bit of a smell, but the names are consistent and I like to declare them at the top of the function.
Maybe it isn't worth adding this functionality to shoestring... without handling select elements, the val
method would only be several lines instead of possibly 50. In my current situation, I'm happy to just handle the selected functionality myself in the app.
This doesn't address the writing of values to multiple selects (ala jQuery's .val( value )
), but looking at the existing code I don't think it would require much more code to support that. However, again it's adding code for quite a specific case.