<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function IsChecked(chk) {
if (TotalChecked() > 3) {
alert('Only 3 boxes can be checked!');
$(chk).prop("checked", false);
return;
}
SetPosition();
}
function TotalChecked() {
var total = 0;
$(".chk").each(function () {
if ($(this).prop("checked")) {
total++;
}
});
return total;
}
function SetPosition() {
var items = [];
//Get the items and their values first
$(".position").each(function () {
var id = $(this).attr('id');
var val = $(this).val();
var item = { id: id, value: val };
var chk = $("#" + id.replace("p", "c"));
if ($(chk).prop("checked")) {
items.push(item);
}
});
//Sort items
items.sort(function (a, b) {
return a.value - b.value;
});
$(".position").each(function () {
var id = $(this).attr('id');
var chk = $("#" + id.replace("p", "c"));
var len = items.length;
if ($(chk).prop("checked")) {
var val = $(this).val();
if (len == 0) {
if (val == 0) { val++ };
}
else if (len == 1) {
items[0].value = 1;
}
else if (len == 2) {
items[0].value = 2;
items[1].value = 1;
}
else {
items[0].value = 3;
items[1].value = 2;
items[2].value = 1;
}
}
else {
$(this).val(0);
}
});
var i;
for (i = 0; i < items.length; i++) {
$("#" + items[i].id).val(items[i].value);
}
}
</script>
</head>
<body>
<input id="c1" onchange="IsChecked(this)" class="chk" type="checkbox" />
<input id="p1" class="form-control position" type="text" value="0" /><br />
<input id="c2" onchange="IsChecked(this)" class="chk" type="checkbox" />
<input id="p2" class="form-control position" value="0" /><br />
<input id="c3" onchange="IsChecked(this)" class="chk" type="checkbox" />
<input id="p3" class="form-control position" value="0" /><br />
<input id="c4" onchange="IsChecked(this)" class="chk" type="checkbox" />
<input id="p4" class="form-control position" value="0" /><br />
<hr />
<p id="message"></p>
</body>
</html>
ASKER
however it does not allow the order selected to be reversed.
JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.
TRUSTED BY
ASKER
Here is what I ended up with - w3schools example.
Open in new window