Reputation: 1479
I have a form below where when a user selects a sport, it is dynamically added. I have implemented code where if a sport is already there, it can not be added again. What I cant figure out is if a user unchecks a sport, I want it removed from the list and the array to and the user is able to add it again.
<!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>
Upvotes: 0
Views: 2454
Reputation: 61143
Here's how you might remove items from the list. Note that I've made several changes to your code... I've changed the checkbox ID to class--IDs must be unique. I've added labels around your checkboxes to make them more accessible and to make the labels clickable. I've removed the
tags after the inputs. Use CSS instead for easier formatting and to simplify the necessary jQuery.
//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 += "<label class=\"wList\"><input checked =\"checked\" class=\"wList-chk\" name=\"wList[]\" type=\"checkbox\" value=\"" + this.value + "\"> " + this.value + "</label>";
}
});
//remove sport when unchecked
$(document).on("change", ".wList-chk", function () {
if ($(this).attr('checked')) {
return;
} else {
$(this).parent('.wList').remove();
}
});
//submit should send checked sports
You should be able to remove the item from your array with something like this:
//remove sport when unchecked
$(document).on("change", ".wList-chk", function () {
if ($(this).attr('checked')) {
return;
} else {
var thisVal = $(this).val();
var index= $.inArray(thisVal, allVals);
allVals.splice(index,1); alert(allVals);
$(this).parent('.wList').remove();
}
});
I've left some alerts in place to monitor the array.
Upvotes: 1