Reputation: 1056
http://jsfiddle.net/xuAQv/ <-- Link to my bad code on JsFiddle.
So i found this bit of code which coverts traditional form select boxes into their twitter bootstrap styled versions. It essentially just hides the select, and creates the html for a select box using bootstrap's css / js.
http://blog.iamjamoy.com/convert-select-boxes-to-a-fancy-html-dropdown I customized the plugin a bit to change the appearance of the drop downs.
The problem i have now is that the $("#mySelect").change(function(){}); no longer fires. I tried adding .live to it, and .on to it, without any luck.
Do i need to modify the plugin? Here is my code for the plugin..
/*!
* Convert <select> elements to Dropdown Group
*
* Author: John Rocela 2012 <[email protected]>
* Customized: Frank B 3/2012
*/
jQuery(function ($) {
$('select').each(function (i, e) {
if (!($(e).data('convert') == 'no')) {
//get some initial data...
xSelect = $(e).attr('id')
xLabel = $("#" + xSelect + " option:selected").text();
xClass = $(e).data('class')
$(e).hide().wrap('<div class="btn-group" id="select-group-' + i + '" />');
var select = $('#select-group-' + i);
select.html('<a class="btn dropdown-toggle ' + xClass + '" data-toggle="dropdown" href="javascript:;">' + xLabel + ' <span class="caret"></span></a><ul class="dropdown-menu"></ul><input type="hidden" value="' + $(e).val() + '" name="' + $(e).attr('name') + '" id="' + $(e).attr('id') + '" class="' + $(e).attr('class') + '" />');
$(e).find('option').each(function (o, q) {
select.find('.dropdown-menu').append('<li><a href="javascript:;" data-title="' + $(q).text() + '" data-value="' + $(q).attr('value') + '">' + $(q).text() + '</a></li>');
if ($(q).attr('selected')) select.find('.dropdown-menu li:eq(' + o + ')').click();
});
select.find('.dropdown-menu a').click(function () {
select.find('input[type=hidden]').live().val($(this).data('value')).change();
select.find('.btn:eq(0)').html($(this).text() + ' <span class="caret"></span>');
});
}
});
});
Upvotes: 1
Views: 4090
Reputation: 78690
If you have a look at what is actually happening in the code, the select is being replaced by a hidden input. When you change the value, that is what is getting change()
called on it. You will need to use event delegation. Something like this:
$("<parent selector>").on("change","#mySelect", function(){});
Where <parent selector>
is a selector matching some parent of the select which is not replaced. If needed it can be the document
but ideally you want it to be as far down the tree as possible.
The reason your live
didn't work is because it should have been like this:
$("#mySelect").live("change", function(){});
Though you should not use live
if you are using the latest jquery, you should use on
.
EDIT: Updated your fiddle: http://jsfiddle.net/xuAQv/2/
Upvotes: 2