I'm having difficulty changing the value of select box in Zurb's foundation. I'm using the custom forms which just hides the actual select box and uses an unordered list as the select box. My problem is that the usual method of changing the value of select box doesn't work:
$('#selectboxID').val('something')
The code above assumes that the value of each of the options in the select box is the same with the text:
<option value="1">1</option>
I also tried:
$($('.dropdown ul li')[1]).addClass('current')
$($('.dropdown ul li')[0]).removeClass('current') //remove current class from the other one
But it doesn't work either.
There's also alternative use case when you're binding on change event yourself, you might not want to trigger it. Code to just force a refresh on select:
Foundation.libs.forms.refresh_custom_select(@jQueryElement, true)
where @jQueryElement is a original hidden select.
You have to trigger "change" event after changing selected index.
Example:
// Change selected option
$('#selectboxID').val('something');
// Or use selectedIndex: $("#selectboxID")[0].selectedIndex = 0;
// Fire change event
$('#selectboxID').trigger('change');
Hope this helps
There have been some modifications to the way that the change event is handled recently in the Foundation code.
You can still achieve what you want using the trigger() method, but you have to add a 'force refresh' flag:
$('#selectboxID').trigger('change', true);
Updated to the latest Foundation 3 release.
Setting selectedIndex
, using JQuery's val()
or anything which triggers a change
event is working out of the box.
This seems to be a regression. As a - hopefully temporary - workaround you can force to update the custom select by using the refresh_custom_selection
method, e.g.:
Foundation.libs.forms.refresh_custom_selection($('select'))
Note: It is refresh_custom_selection
, not refresh_custom_select
!
It is not necessary to use the latter (or trigger('change', true)
) because they both completely rebuild the custom select, i.e. they re-copy your select options which involves lots of DOM manipulation and it can slow things down a lot. (Depending on the size of your select options and your other code)
On the other hand refresh_custom_selection
just updates the displayed value which is a much more lightweight operation.
PS: Instead of refresh_custom_selection
you could also use
$('a.current', $select.next()).text($('option:selected', $select).text());
But that code makes assumptions on the generated HTML, so it is better to stick to the provide utility methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With