How does JavaScript implement the movement of elements in a combo list box

  • 2021-01-19 21:55:37
  • OfStack

Let me first tell you the difference between a combo box and a list box:

Combo boxes include the functionality of list boxes and text boxes

Text box: only data can be entered

List box: Only data can be selected

Combo box: It can enter data and select ' '

Application background: There are two list boxes on the page. You need to move elements from one list box to the other.

The basic idea of implementation:

(1) Write init method to initialize two list boxes;

(2) To add onload event to body, call init method;

(3) Write move (s1,s2);

(4) Write moveAll (s1,s2) Move all options in s1 to s2.

(5) Add onclick event for button.

The javascript code is as follows:


<script type="text/javascript" language="javascript">
// Initialize the drop-down box information 
function init() {
for (i = ; i < ; i++) {
var y = document.createElement("option");// increase 1 An element option
y.text = ' options ' + i;
var x=document.getElementById("s");// According to the ID Find the list box 
x.add(y, null); //
}
}
// Move the selected option to another 1 edge 
function move(s, s) {
var index = s.selectedIndex;
if (index == -) {
alert(" No selected value ");
return;
}
s.length++;
s.options[s.length - ].value = s.options[index].value;
s.options[s.length - ].text = s.options[index].text;//s Assigns the currently selected value to s At the end of the 1 An element 
s.remove(index);// from s Removes the current element from 
}
// the 1 The side moves completely over to the other side 1 edge 
function moveAll(s, s) {
if (s.length == ) {
alert(" No options available ");
return;
}
s.length = s.length + s.length;
for (var i = ; i < s.length; i++) {
s.options[s.length - s.length + i].value = s.options[i].value;
s.options[s.length - s.length + i].text = s.options[i].text;
}
s.length = ;
}
</script> 

< body > Code:


<body onload="init()">
<table>
<tr>
<td><select id="s" size= style="width:"></select></td>
<td><input type="button" name="moveToRight" value=">"
onClick="move(s,s)"> <br>
<br> <input type="button" name="moveAllToRight" value=">>"
onClick="moveAll(s,s)"> <br> <input type="button"
name="moveToLeft" value="<" onClick="move(s,s)"> <br>
<br> <input type="button" name="moveAllToLeft" value="<<"
onClick="moveAll(s,s)"></td>
<td><select id="s" name="s" size= style="width:"></select></td>
</tr>
</table>
</body>

The above content introduces the JavaScript how to achieve the combined list box element movement effect of the relevant knowledge, I hope to be helpful to you!


Related articles: