mover select options with jquery
by Seungrae Lee
HTML
<table>
<tr>
<td>
<select id="listbox" size="10">
<option value="10100">--</option>
<option value="10101">A</option>
<option value="10102">B</option>
<option value="10103">C</option>
</select>
</td>
<td valign="top">
<input type="button" value="Up">
<br />
<input type="button" value="Down">
<br />
<input type="button" value="Delete">
<br />
<input type="button" value="Reset">
</td>
</tr>
</table>
<table cellpadding="2" id="tbl1">
<tr>
<td>LIST_CODE</td>
<td>LIST_OUT</td>
<td>LIST_ORDER</td>
<td></td>
</tr>
<tr>
<td>
<input type="text" name="listCode" maxlength="5" size="10">
</td>
<td>
<input type="text" name="listOut" size="10">
</td>
<td><span id="order"></span>
</td>
<td>
<input type="button" value="Add">
<input type="button" value="Update" disabled="disabled">
</td>
</tr>
</table>
<div id="messages"></div>
CSS
#listbox {
width: 100px;
}
#tbl1 {
font-size: 10pt;
}
#tbl1 td {
text-align: center;
}
#messages {
color: #f00;
}
JavaScript
$(function () {
// move up
$('input[type="button"][value="Up"]').click(function () {
var $op = $('#listbox option:selected');
if ($op.length) {
$op.prev().before($op);
$('#order').text($('#listbox').get(0).selectedIndex);
}
});
// move down
$('input[type="button"][value="Down"]').click(function () {
var $op = $('#listbox option:selected');
if ($op.length) {
$op.next().after($op);
$('#order').text($('#listbox').get(0).selectedIndex);
}
});
// display selected option
$('#listbox').change(function () {
var $op = $(this).find('option:selected');
//log
$('#messages').text($op.html());
$('input[name="listCode"]').val($(this).val());
$('input[name="listOut"]').val($op.text());
$('#order').text($(this).get(0).selectedIndex);
$('input[type="button"][value="Update"]').removeAttr("disabled");
});
// Add
$('input[type="button"][value="Add"]').click(function () {
var value = $('input[name="listCode"]').val(),
label = $('input[name="listOut"]').val();
if (value === '' || label === '') {
$('#messages').text('input required field.');
return;
}
$('#listbox').append($('<option/>').val(value).text(label).attr('selected', 'selected'));
});
// Update
$('input[type="button"][value="Update"]').click(function () {
var value = $('input[name="listCode"]').val(),
label = $('input[name="listOut"]').val();
$('#listbox option:selected').val(value).text(label);
});
// Reset
$('input[type="button"][value="Reset"]').click(function () {
reset();
});
function reset() {
var options = {
'10100': '--',
'10101': 'A',
'10102': 'B',
'10103': 'C'
};
$("#listbox option").remove();
...