Created
July 12, 2010 15:39
-
-
Save mgax/472607 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Checkboxes to dropdown</title> | |
</head> | |
<body> | |
<script src="jquery-1.4.2.min.js"></script> | |
<input type="checkbox" name="question" value="0" id="question_0" /> | |
<label for="question_0">Red</label> | |
<br /> | |
<input type="checkbox" name="question" value="1" id="question_1" /> | |
<label for="question_1">Green</label> | |
<br /> | |
<input type="checkbox" name="question" value="2" id="question_2" checked="checked" /> | |
<label for="question_2">Blue</label> | |
<br /> | |
<script> | |
$(function() { | |
function checkboxes_to_dropdown(input_name) { | |
var checkboxes = $("input[type=checkbox][name='"+input_name+"']"); | |
var the_ul = $('<ul>').addClass("current-selection"); | |
var the_select = $('<select><option value="">-- select value --' + | |
'</option></select>'); | |
$([the_ul, the_select]).insertBefore(checkboxes.first()); | |
checkboxes.each(function() { | |
var checkbox = $(this); | |
var label = checkbox.next('label'); | |
var option = $('<option>').text(label.text()); | |
option.attr('value', checkbox.attr('value')); | |
the_select.append(option); | |
if(checkbox.is(':checked')) { | |
selected(option); | |
} | |
checkbox.next('label').next('br').remove(); | |
checkbox.next('label').remove(); | |
checkbox.remove(); | |
}); | |
the_select.change(function(evt) { | |
var option = $('option:selected', the_select); | |
if(option.val() == "") return; | |
selected(option); | |
}); | |
function selected(option) { | |
var remove_button = $('<a href="javascript:;">[remove]</a>'); | |
remove_button.css({color: '#a00', 'font-size': '80%'}); | |
remove_button.click(function() { | |
selected_li.remove(); | |
option.attr('disabled', null); | |
}); | |
var hidden_input = $('<input type="hidden">').attr({ | |
name: input_name, | |
value: option.attr('value') | |
}); | |
var selected_li = $('<li>').append( | |
option.text(), ' ', remove_button, hidden_input); | |
option.attr('disabled', 'disabled'); | |
$('option', the_select)[0].selected = true; | |
the_ul.append(selected_li); | |
} | |
} | |
checkboxes_to_dropdown('question'); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment