JQuery operates on options of Select moving up and down removing additions and so on

  • 2020-03-29 23:48:11
  • OfStack

 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 

<script type="text/javascript" src="jquery-1.9.1.min.js"></script> 

<script type="text/javascript"> 
 
function upSelectedOption(){ 
if(null == $('#where').val()){ 
alert(' Please select one item '); 
return false; 
} 
//The selected index, starting at 0
var optionIndex = $('#where').get(0).selectedIndex; 
//If it is not at the top, it can be moved
if(optionIndex > 0){ 
$('#where option:selected').insertBefore($('#where option:selected').prev('option')); 
} 
} 

 
function downSelectedOption(){ 
if(null == $('#where').val()){ 
alert(' Please select one item '); 
return false; 
} 
//The length of the index, starting at 1
var optionLength = $('#where')[0].options.length; 
//The selected index, starting at 0
var optionIndex = $('#where').get(0).selectedIndex; 
//If it is not at the bottom, it can go down
if(optionIndex < (optionLength-1)){ 
$('#where option:selected').insertAfter($('#where option:selected').next('option')); 
} 
} 

 
function removeSelectedOption(){ 
if(null == $('#where').val()){ 
alert(' Please select one item '); 
return false; 
} 
$('#where option:selected').remove(); 
} 

 
function getSelectedOption(){ 
//Gets the Text of the Select selection
var checkText = $('#where').find('option:selected').text(); 
//Gets the Value of the Select
var checkValue = $('#where').val(); 
alert(' Currently selected text=' + checkText + ', value=' + checkValue); 
var ids = ''; 
var options = $('#where')[0].options; 
for(var i=0; i<options.length; i++){ 
ids = ids + '`' + options[i].id; 
} 
alert(' The currently selected numbering order is ' + ids); 
} 

 
function addSelectedOption(){ 
//Add in the first location
$('#where').prepend('<option value="hbin" id="where06">Haerbin</option>'); 
//Add in the last position
$('#where').append('<option value="hlj" id="where07">HeiLongJiang</option>'); 
$('#where').attr('size', 7); 
} 
</script> 

<div id="updown"> 
<select id="where" name="where" size="5"> 
<option value="hk" id="where01">Hong Kong</option> 
<option value="tw" id="where02">Taiwan</option> 
<option value="cn" id="where03">China</option> 
<option value="us" id="where04">United States</option> 
<option value="ca" id="where05">Canada</option> 
</select> 
</div> 
<br/> 
<input type="button" value=" Move up " onclick="upSelectedOption()"/> 
<input type="button" value=" Move down " onclick="downSelectedOption()"/> 
<input type="button" value=" delete " onclick="removeSelectedOption()"/> 
<input type="button" value=" determine " onclick="getSelectedOption()"/> 
<input type="button" value=" add " onclick="addSelectedOption()"/> 

Related articles: