<form id="frm" action="" method="post">
Select list:<br/>
<select name="sel_list" id="sel_list" size="2" onchange="adOption.selOpt(this.value, 'optval')"></select><br/><br/>
Add an option: <input type="text" name="optval" id="optval" /><br /><br/>
<input type="button" id="addopt" name="addopt" value="Add Option" onclick="adOption.addOption('sel_list', 'optval');" />
<input type="button" id="del_opt" name="del_opt" value="Delete Option" onclick="adOption.delOption('sel_list', 'optval');" />
</form>
<script type="text/javascript"><!--
// Free JavaScript course - coursesweb.net
// create the object with methods to add and delete <option></option>
var adOption = new Object();
// method that check if the option is already in list
// receives the id of the <select></select> list, and box with the value for <option>
adOption.checkList = function(list, optval) {
var re = 0; // variable that will be returned
// get the <option> elements
var opts = document.getElementById(list).getElementsByTagName('option');
// if the option exists, sets re=1
for(var i=0; i<opts.length; i++) {
if(opts[i].value == document.getElementById(optval).value) {
re = 1;
break;
}
}
return re; // return the value of re
};
// method that adds <option>
adOption.addOption = function(list, optval) {
// gets the value for <option>
var opt_val = document.getElementById(optval).value;
// check if the user adds a value
if(opt_val.length > 0) {
// check if the value not exists (when checkList() returns 0)
if(this.checkList(list, optval) == 0) {
// define the <option> element and adds it into the list
var myoption = document.createElement('option');
myoption.value = opt_val;
myoption.innerHTML = opt_val;
document.getElementById(list).insertBefore(myoption, document.getElementById(list).firstChild);
document.getElementById(optval).value = ''; // delete the value added in text box
}
else alert('The value "'+opt_val+'" already added');
}
else alert('Add a value for option');
};
// method that delete the <option>
adOption.delOption = function(list, optval) {
// gets the value of <option> that must be deleted
var opt_val = document.getElementById(optval).value;
// check if the value exists (when checkList() returns 1)
if(this.checkList(list, optval) == 1) {
// gets the <option> elements in the <select> list
var opts = document.getElementById(list).getElementsByTagName('option');
// traverse the array with <option> elements, delete the option with the value passed in "optval"
for(var i=0; i<opts.length; i++) {
if(opts[i].value == opt_val) {
document.getElementById(list).removeChild(opts[i]);
break;
}
}
}
else alert('The value "'+opt_val+'" not exist');
}
// method that adds the selected <option> in text box
adOption.selOpt = function(opt, txtbox) { document.getElementById(txtbox).value = opt; }
--></script>
hasilnya
-->
Tidak ada komentar:
Posting Komentar