I have the following code with the logic I want as follows:
- A user can not select a sport twice. A user may have sports saved in the database and with that in mind, the database records will be loaded and displayed and the user is allowed to add additional sports as longer as they do not appear in the list. Right now I have set Baseball as coming from the database but when I select it again, my logic is allowing the user to add it again. What I am doing wrong?
JSFIDDLE: http://jsfiddle.net/Jrqqq/
var allVals = [{ id: 1, value: "Baseball"}];
$.each(allVals, function (k, v) {
$("#results").append("<label class=\"wList\"><input checked=\"checked\" class=\"wList-chk\" name=\"wList[]\" type=\"checkbox\" value=\""
+ v.id
+ "\">"
+ v.value
+ "</label>");
});
$(function () {
var sports = [{ id: 1, value: "Baseball" },
{ id: 2, value: "Soccer" },
{ id: 3, value: "Basketball" },
{ id: 4, value: "Volleyball" },
{ id: 5, value: "Tennis" },
{ id: 6, value: "Running" },
{ id: 7, value: "Swimming"}];
$("#sports").autocomplete({
source: sports,
select: function (event, ui) {
if ($.inArray(ui.item.id, allVals) == -1) {
allVals.push(ui.item.id);
$("#results")
.append("<label class=\"wList\"><input checked=\"checked\" class=\"wList-chk\" name=\"wList[]\" type=\"checkbox\" value=\""
+ ui.item.id
+ "\">"
+ ui.item.value
+ "</label>");
$('input.wList-chk[type="checkbox"][value="' + ui.item.id + '"]').parent().effect('highlight', {}, 1500);
ui.item.value = "";
}
else {
ui.item.value = "";
$('input.wList-chk[type="checkbox"][value="' + ui.item.id + '"]').parent().effect('highlight', {}, 1500);
}
}
});
});
$(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);
$(this).parent('.wList').remove();
}
});
It looks like you’re not adding the baseball id to the
allValsarray.