我在下面有一个表格,当用户选择一项运动时,它会被动态添加。我已经实现了代码,如果一项运动已经存在,则不能再次添加。我想不通的是,如果用户取消选中一项运动,我希望它从列表和数组中删除,并且用户能够再次添加它。
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Item listing</title>
</head>
<body>
<form action="test.htm" method="get">
<select name="mylist" id="myList">
<option id="1">Baseball</option>
<option id="2">Soccer</option>
<option id="3">Basketball</option>
<option id="4">Volleyball</option>
<option id="5">Hockey</option>
<option id="6">Football</option>
<option id="7">Rugby</option>
</select>
<br />
<div id="sList">
</div>
<br />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
//add item when selected
//a sport can not be added twice
var allVals = [];
$('#myList').change(function () {
if ($.inArray(this.value, allVals) == -1) {
allVals.push($(this).val());
document.getElementById("sList").innerHTML += "<input checked =\"checked\" id=\"wList\" name=\"wList[]\" type=\"checkbox\" value=\"" + this.value + "\">" + this.value + "<br />";
}
});
//remove sport when unchecked
$('#wList').change(function () {
//???
});
//submit should send checked sports
</script>
</body>
</html>