Skip to content

Instantly share code, notes, and snippets.

@pudly
Created July 16, 2012 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pudly/3124109 to your computer and use it in GitHub Desktop.
Save pudly/3124109 to your computer and use it in GitHub Desktop.
Select replacement jQuery walkthrough
<!doctype html>
<html>
<head>
<title>Example &lt;select&gt; replacement</title>
</head>
<body>
<form action="" method="post">
<label for="param_interest">I want to...</label>
<select name="interest" id="param_interest">
<option value="attend">Attend</option>
<option value="present">Present</option>
<option value="volunteer">Volunteer</option>
</select>
</form>
</body>
</html>
// Select replacement
$('select').each(function() {
// variables
var $this = $(this);
var $form = $this.parents('form').eq(0);
var id = $this.attr('id');
var name = $this.attr('name');
// hide and null the existing select
$this.attr({'id' : '', 'name' : ''}).hide();
// create new ul to replace select
$this.after('<ul class="select"></ul>')
// var for new ul
var $select = $this.next('ul').eq(0);
$select.wrap('<div class="select-container" />')
// set data attribute for the consistent name
$select.data('name', name);
// currently selected (first) option
$select.append('<li class="current">' + $('option', $this).eq(0).val() + '</li>');
// duplicate all options in select to ul
$('option', $this).each(function() {
$select.append('<li>' + $(this).val() + '</li>');
})
// add hidden field to form to capture value from ul
$form.append('<input type="hidden" name="' + name + '" value="' + $('option', $this).eq(0).val() + '" />' );
})
$('.select li.current').click(function() {
$(this).parents('ul.select').toggleClass('active');
})
$('.select li:not(.current)').click(function() {
var $this = $(this);
var $select = $this.parents('ul').eq(0);
var $hidden = $('input[name=' + $select.data('name') + ']');
var $current = $('.current', $select);
$current.text($this.text());
$select.removeClass('active');
$hidden.val($this.text());
})
// global blur state
$('body, html').mouseup(function(){
if($('.select.active').length !=0) $('.select.active').removeClass('active');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment