Skip to content

Instantly share code, notes, and snippets.

@liply

liply/index.html

Created Apr 17, 2016
Embed
What would you like to do?
jsstudy
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function createSelectionBox(id, fruits, selected, masterFruits){
var html = '<select id="select' + id + '">';
if(selected === -1){
html += '<option value="-1" selected>---</option>';
}else{
html += '<option value="-1">---</option>';
}
for(var n = 0; n < fruits.length; ++n){
if(n === selected){
html += '<option value="' + n + '" selected>' + masterFruits[n] + '</option>';
}else if(fruits[n]){
html += '<option value="' + n + '">' + fruits[n] + '</option>';
}
}
html += '</select>';
return html;
}
function createSelectionGroup(fruits, selected, masterFruits){
var html = "";
for(var n = 0; n < fruits.length; ++n){
html += createSelectionBox(n, fruits, selected[n], masterFruits);
}
return html;
}
function extractSelectedFruitsIndex(length){
var indices = [];
for(var n = 0; n < length; ++n){
var select = document.querySelector('#select' + n);
var value = select.options[select.selectedIndex].value;
indices.push(parseInt(value));
}
return indices;
}
function removeFruits(fruits, selected){
var result = fruits.slice();
for(var n = 0; n < selected.length; ++n){
result[selected[n]] = null;
}
return result;
}
function createOnChangeHandler(fruits){
return function(){
var selected = extractSelectedFruitsIndex(fruits.length);
var fruitsRemoved = removeFruits(fruits, selected);
document.querySelector('#box').innerHTML = createSelectionGroup(fruitsRemoved, selected, fruits);
setOnChangeHandler(fruits);
}
}
function setOnChangeHandler(fruits){
for(var n = 0; n < fruits.length; ++n){
document.querySelector('#select' + n).onchange = createOnChangeHandler(fruits);
}
}
window.onload = function(){
var fruits = ['りんご', 'レモン', 'みかん', 'たまねぎ', 'すいか'];
var selected = [-1,-1,-1,-1,-1];
document.querySelector('#box').innerHTML = createSelectionGroup(fruits, selected, fruits);
setOnChangeHandler(fruits);
}
</script>
<div id="box"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment