How to use checkbox as radio button for calculate total - javascript

I have below options, I want to use 1,2,3 options as radio button.
[checkbox] option 1 : $100
[checkbox] option 2 : $200
[checkbox] option 3 : $300
[checkbox] Registration fee : $50
Total = Option + Registration fee;
After selecting check box, value should be added into total and after unchecking, value should be deductefromtotal`. but the challenge is I want to use option 1,2 and 3 as radio buttons (only one option should be selected one time). But if I am using standard radio buttons for options then value is including in total on select but not deducting old options value from total if i select new option.
I used this code
<script type="text/javascript">
var total = 0;
function fee(item) {
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total + "";
}
</script>
HTML
<input id="checkbox1" type="checkbox" name="program1" value="100" onClick="fee(this);"/>
<input id="checkbox2" type="checkbox" name="program2" value="200" onClick="fee(this);"/>
<input id="checkbox3" type="checkbox" name="program3" value="300" onClick="fee(this);"/>
<input id="checkbox4" type="checkbox" name="fee" value="50" onClick="fee(this);"/>

I assume you need at least one of them.
Radios will uncheck if they have the same name:
function calc() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg"),
total = document.getElementById("total"),
tot = 0;
for (var i=0;i<rads.length;i++) {
tot+=rads[i].checked?parseInt(rads[i].value,10):0;
}
if (reg.checked) tot += parseInt(reg.value,10);
total.value=tot;
}
window.onload=function() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg");
for (var i=0;i<rads.length;i++) {
rads[i].onclick=calc;
}
reg.onclick=calc;
}
<input type="radio" name="option" id="option1" value="100" />100
<input type="radio" name="option" id="option2" value="200" />200
<input type="radio" name="option" id="option3" value="300" />300 <br/>
<input type="checkbox" name="reg" id="reg" value="50" />50<br/>
Total <input type="text" readonly id="total" /><br/>
The name and concept of "radio button" comes from the old car radios where pressing one button would make the other button reset:

I don't want to discuss about how your design is probably wrong.
But I like to introduce a solution that does not imply some javascript to disable all checkbox and only allow one to be selected.
By changing the style of a radio button to look like a checkbox, you can easily achieve what you are asking.
form > input[type="radio"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
}
<form>
<input type="radio" name="program" value="100" /> program1<br />
<input type="radio" name="program" value="200" /> program2<br />
<input type="radio" name="program" value="300" /> program3<br />
<input type="checkbox" name="fee" value="50" /> fee
</form>
You SHOULD not use this and think of using some radio button. This is counter intuitive for users.

try this:
function fee(ev) {
var total = 0;
var item = ev.target;
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total;
}
document.querySelector('form').addEventListener('change', fee);
<div id='Totalcost'>0000</div>
<form>
<input type="radio" name='name' value="100">option1(100£)
<br>
<input type="radio" name='name' value="200">option2(200£)
<br>
</form>
using form and change event the code is more concise

Personally I would use a simple MVVM library for this, Vue.js is a rather simple example.
This way you don't have to use your DOM as a datastore and both your presentation and your logic are separated rather clearly.
var v = new Vue({
el: 'body',
data: {
checkboxes: [{
name: 'first',
value: 100,
checked: false
}, {
name: 'second',
value: 200,
checked: false
}, {
name: 'third',
value: 300,
checked: false
}],
optional: {
name: 'optional',
value: 50,
checked: false
}
},
methods: {
foo: function() {
var sum = this.checkboxes.reduce(function(sum, item) {
return sum + (item.checked ? item.value : 0);
}, 0);
sum += this.optional.checked ? this.optional.value : 0;
return sum;
},
bar: function(e) {
if (e.targetVM.checked) {
this.checkboxes.forEach(function(checkbox) {
checkbox.checked = false;
});
e.targetVM.checked = true;
}
}
}
});
ul {
list-style: none;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.12/vue.min.js"></script>
<ul>
<li v-repeat="checkboxes">
<input type="checkbox" id="checkbox_{{name}}" v-model="checked" v-on="click: bar" />
<label for="checkbox_{{name}}">{{name}}: {{value}}</label>
</li>
</ul>
<input type="checkbox" v-model="optional.checked" id="optional_{{optional.name}}" />
<label for="optional_{{optional.name}}">{{optional.name}}</label>
<p>Total: <span v-text="foo()"></span>
</p>

I think this is pretty straight forward.
$(".total").html("$" + (parseInt($(this).val()) + 500));
Made a small fiddle for you here.

Try something like below, would require a lot of clean up.
$(document).ready(function() {
//set initial state.
var fee= 50;
$('#val1').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val1').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val2').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val3').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
});

Related

Check all/sum values - how to put span inside input

I wrote some code which sums up all the values of checkboxes with a "toggle all" option. At the beginning I needed to only have information about the value, but now I need to have sum inside an input element, but it does not work.
NOTICE: I know ID can be used only once! I put both input and span to show that it works with span and not with input.
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total')
function sumUpdate() {
totalElement.innerHTML = inputs.reduce(function(result, input) {
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(2);
}
// Update the sums in function on input change.
inputs.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/></div> <br/> Price: <span id="payment-total">0</span>
</div>
I done some modification to your sumUpdate function making it working now, you need to give the input control and the span different id:
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var values = document.querySelectorAll('.sum');
function sumUpdate() {
var total = 0;
var selectedItems = Array.prototype.filter.call(values,function(input) {
return input.checked ? input : null;
});
$(selectedItems).each(function (index, element) {
total = total + parseFloat($(element).val());
});
total = parseFloat(total).toFixed(2);
$('#payment-total').val(total);
$('#payment-total-span').text(total);
}
// Update the sums in function on input change.
values.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/> <br/> Price: <span id="payment-total-span">0</span>
</div>

value of input changes div's content dynamically [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
im kinda new to javascript. I would like to multiple the total value by the days value dynamically. Was trying for some time but couldnt find the solution. Thanks in advance.
$(document).ready(function() {
$('.kalorie').click(function() {
var varKalorie = $('input[name=kalorie]:checked').val()
$('.posilki').prop("disabled", false);
if (varKalorie == 1000) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val());
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total);
});
}
if (varKalorie == 1250) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.1;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 1500) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.2;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 2000) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.4;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 2500) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.6;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
});
console.log($('#total').text());
// This button will increment the value
$('.qtyplus').click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name=' + fieldName + ']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name=' + fieldName + ']').val(0);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2 class="global-title">Cennik</h2>
<input type="radio" name="kalorie" class="kalorie" value="1000" />1000
<input type="radio" name="kalorie" class="kalorie" value="1250" />1250
<input type="radio" name="kalorie" class="kalorie" value="1500" />1500
<input type="radio" name="kalorie" class="kalorie" value="2000" />2000
<input type="radio" name="kalorie" class="kalorie" value="2500" />2500
<br/>
<br/>
<input type="checkbox" class="posilki" value="15" disabled/>Śniadanie
<input type="checkbox" class="posilki" value="10" disabled/>2 Śniadanie
<input type="checkbox" class="posilki" value="20" disabled/>obiad
<input type="checkbox" class="posilki" value="10" disabled/>podwieczorek
<input type="checkbox" class="posilki" value="15" disabled/>kolacja
<br/>Days
<input type='button' value='-' class='qtyminus' field='quantity' disabled/>
<input type='text' name='quantity' value='30' class='qty' id="days-input" disabled/>
<input type='button' value='+' class='qtyplus' field='quantity' disabled/>
<br/>
<br/>Total:
<div id="total">0 zł</div>
</div>
Since you mention are kind of new to javascript ... my main message is to put things in functions.
This obliges you to think: "okay, what exactly do I need to know to perform this?" ... well those are the parameters of your function.
Ad of course, functions dramatically reduces code, you don't have to copy/paste everything 6 times.
Notice: you could put all the functions within document.ready, if you want.
And, oh yes, I added label elements. This makes it nicer to the client.
Is this it?
<div class="container">
<h2 class="global-title">Cennik</h2>
<input type="radio" name="kalorie" class="kalorie" value="1000" id="r0" /><label for="r0">1000</label>
<input type="radio" name="kalorie" class="kalorie" value="1250" id="r1" /><label for="r1">1250</label>
<input type="radio" name="kalorie" class="kalorie" value="1500" id="r2" /><label for="r2">1500</label>
<input type="radio" name="kalorie" class="kalorie" value="2000" id="r3" /><label for="r3">2000</label>
<input type="radio" name="kalorie" class="kalorie" value="2500" id="r4" /><label for="r4">2500</label>
<br/><br/>
<input type="checkbox" class="posilki" id="sniadanie" value="15" ><label for="sniadanie">Sniadanie</label>
<input type="checkbox" class="posilki" id="sniadanie2" value="10" ><label for="sniadanie2">2 Sniadanie</label>
<input type="checkbox" class="posilki" id="obiad" value="20" ><label for="obiad">obiad</label>
<input type="checkbox" class="posilki" id="podwieczorek" value="10" ><label for="podwieczorek">podwieczorek</label>
<input type="checkbox" class="posilki" id="kolacja" value="15" ><label for="kolacja">kolacja</label>
<br/><br/>Days
<input type="button" value="-" class="qtyminus" field="quantity" >
<input type="text" name="quantity" value="30" class="qty" id="days-input" >
<input type="button" value="+" class="qtyplus" field="quantity" >
<br/>
<br/>Total:
<div id="total">0 zl</div>
</div>
<style>
label {
cursor: pointer;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// calculates the total price, displays it in id="total"
function calculateTotal(sum_price, days) {
var result = sum_price * days;
$('#total').html(result + ' zl');
return result; // not really being used
}
// reads the checked checkboxes, returns their sum value
function readSumPrice() {
var sum = 0;
$('.posilki').each(function(i) {
if(this.checked) {
sum += Number($(this).val());
}
});
return sum;
}
// what ever the client changes, triggers this function. We don't really care what has just been clicked on, we have to recalculate it anyway.
function somethingChanged() {
// first we want to check if three meals have been chosen
var numberOfMealsChosen = $( ".posilki:checked" ).length;
if(numberOfMealsChosen >= 3) {
// now we calculate
var sum_price = readSumPrice();
var days = Number($('#days-input').val());
calculateTotal(sum_price, days);
}
else {
$('#total').html('please choose 3 items');
}
}
// now the events
$(document).ready(function() {
// click on +
$('.qtyplus').click(function() {
var days = Number($('#days-input').val());
$('#days-input').val(days + 1);
somethingChanged();
});
// click on -
$('.qtyminus').click(function() {
var days = Number($('#days-input').val());
// let's put 0 as minimum
if(days > 0) {
$('#days-input').val(days - 1);
somethingChanged();
}
});
// click on checkbox
$('.posilki').click(function() {
somethingChanged();
});
// click on radio. triggers the calculation but doesn't really affect anything (yet?)
$('.kalorie').click(function() {
somethingChanged();
});
});
</script>

Check at most four check box and store checked value to textbox

I am displaying some check boxes. The user can check a maximum of 4 boxes. I store the checked value in 4 textboxes.
My problem: How can I correctly store the "new" checked value when the user randomly unchecks one box and checks another?
I store values as follows: First checked into item_1, second checked into item_2, third checked into item_3 ... If the user unchecks the first checked box, for example, how can I store the value of the next box he or she checks into item_1? Please help.
Simplified code
<input type="checkbox" name="prodname_1" id="prodname_1"value="1"/>
<input type="checkbox" name="prodname_2" id="prodname_2"value="2"/>
<input type="checkbox" name="prodname_3" id="prodname_3"value="3"/>
.
.
<input type="checkbox" name="prodname_10" id="prodname_10"value="10"/>
<input type="text" name="item_0" id="item_0"value=""/>
<input type="text" name="item_1" id="item_1"value=""/>
<input type="text" name="item_2" id="item_2"value=""/>
<input type="text" name="item_3" id="item_3"value=""/>
$(document).ready(function (e)
{
counter=0;
$('input[id^="prodname_"]').change(function()
{
id = $(this).attr('id');
var arr = id.split('_');
valueChecked=$('#'+id).val();
if(this.checked)
{
if(counter==4)
{
alert('Allready checked 4 items');
this.checked=false;
return false;
}
$("#item_"+counter).val(valueChecked);
++counter;
}
});
});
Instead of retaining a counter, just count the number of checked boxes when the change occurs.
Revised to use the logic you intended (took a little while to figure that out) :)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/9/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var checkboxes = $('input[id ^= "prodname_"]').change(function () {
var id = $(this).attr('id');
var arr = id.split('_');
valueChecked = $(this).val();
// Count of checked checkboxes
var counter = checkboxes.filter(':checked').length;
if ($(this).is(':checked')) {
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
} else {
// Add to the first available slot
$items.filter(function(){return $(this).val() == ""}).first().val(valueChecked);
}
} else {
// Remove the matching value
$items.filter(function(){return $(this).val() == valueChecked;}).first().val('');
}
});
});
note: The "jQuery way" for changing checkboxes is to use prop('checked', booleanvalue) (also changed above)
V2 - If you don't want gaps:
This version is actually simpler as it just clears the items and fills them, in order, with any checked checkbox values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/13/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var $checkboxes = $('input[id ^= "prodname_"]').change(function () {
// Count of checked checkboxes
var counter = $checkboxes.filter(':checked').length;
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
}
// Clear all the items
$items.val('');
// Fill the items with the selected values
var item = 0;
$checkboxes.filter(':checked').each(function () {
$('#item_' + (item++)).val($(this).val());
});
});
});
Look at
$(document).ready(function(e) {
var counter = 0,
$items = $('input[name^="item_"]');
$('input[id^="prodname_"]').change(function() {
var id = this;
if (this.checked) {
if (counter == 4) {
this.checked = false;
return;
}
$("#item_" + counter).val(this.value).attr('data-value', this.value);
++counter;
} else {
var $item = $items.filter('[data-value="' + this.value + '"]');
var index = $items.index($item);
$items.slice(index, counter).each(function(i) {
var $n = $items.eq(index + i + 1);
$(this).val($n.val() || '').attr('data-value', $n.attr('data-value'));
});
counter--;
$("#item_" + counter).val('').removeAttr('data-value');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="prodname_1" id="prodname_1" value="1" />
<input type="checkbox" name="prodname_2" id="prodname_2" value="2" />
<input type="checkbox" name="prodname_3" id="prodname_3" value="3" />
<input type="checkbox" name="prodname_4" id="prodname_4" value="4" />
<input type="checkbox" name="prodname_5" id="prodname_5" value="5" />
<input type="checkbox" name="prodname_6" id="prodname_6" value="6" />
<input type="checkbox" name="prodname_7" id="prodname_7" value="7" />
<input type="checkbox" name="prodname_8" id="prodname_8" value="8" />
<input type="checkbox" name="prodname_9" id="prodname_9" value="9" />
<input type="checkbox" name="prodname_10" id="prodname_10" value="10" />
<input type="text" name="item_0" id="item_0" value="" />
<input type="text" name="item_1" id="item_1" value="" />
<input type="text" name="item_2" id="item_2" value="" />
<input type="text" name="item_3" id="item_3" value="" />

Limit checkbox based on value JavaScript

I'm trying to create a checkbox limit based on a value change example:
I have the following checkbox
<input type="checkbox" name="checkbox2[]" onClick="setChecks(this)" value="`key`=<?php
echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>" />
I have a lot of check box as this is in a loop. Some have the same value others do not. Anyways wanting to create code that prevents checking boxes with different values!
Current code for limiting checkbox number:
<script>
<!--
//initial checkCount of zero
var checkCount = 0
//maximum number of allowed checked boxes
var maxChecks = 3
var d = document.getElementById('chk' + (j++));
function setChecks(obj) {
//increment/decrement checkCount
if (obj.checked) {
checkCount = checkCount + 1
} else {
checkCount = checkCount - 1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount > maxChecks) {
obj.checked = false
checkCount = checkCount - 1
alert('you may only choose up to ' + maxChecks + ' options')
}
}
// -->
</script>
I tried to edit the final if statement with no luck!
After some messing around i managed to end up with this a working solution!
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
$(function() {
var lastChecked = [];
$(':checkbox').change(function() {
if (this.checked) {
if (lastChecked.length && this.value != lastChecked[0].value) {
this.checked = false;
alert("the last box you checked has a different value");
}
else
{
lastChecked.unshift(this);
}
}
else {
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});
});​
​
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});
});​

Javascript checkbox selection order

How would I go about detecting the order in which checkboxes are checked? I have a list of checkboxes on a form, and I need to have users select their first and second choices (but no more). So, given this:
<input name="checkbox1" type="checkbox" value="a1"> Option 1
<input name="checkbox1" type="checkbox" value="a2"> Option 2
<input name="checkbox1" type="checkbox" value="a3"> Option 3
<input name="checkbox1" type="checkbox" value="a4"> Option 4
If someone selects option 2, then option 3, I'd like to have some indicator that option 2 was the first choice, and option 3 was the second choice. Any ideas?
Thanks in advance.
Update:
These are extremely helpful suggestions, thank you. As I test these examples, it's giving me a better idea of how to approach the problem - but I'm still a bit stuck (I'm a JS novice). What I want to do is have these labels change as the checkboxes are checked or unchecked, to indicate which is the first or second selection:
<label id="lblA1"></label><input name="checkbox1" type="checkbox" value="a1"> Option 1
<label id="lblA2"></label><input name="checkbox1" type="checkbox" value="a2"> Option 2
<label id="lblA3"></label><input name="checkbox1" type="checkbox" value="a3"> Option 3
<label id="lblA4"></label><input name="checkbox1" type="checkbox" value="a4"> Option 4
So if someone clicks Option 2, then Option 3, lblA2 will display "First", and lblA3 will display "Second". If someone unchecks Option 2 while Option 3 is still checked, lblA3 becomes "First". Hopefully this makes sense?
Thanks!
If you are using jQuery. Below code is does what you have explained and it is tested.
I have used global variables.
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
<input type="button" value="do" id="btn" />
As shown below, it also handles the situation that user unchecks a choice.
$(document).ready(function () {
var first = "";
var second = "";
$('input[name="checkbox1"]').change(function () {
if ($(this).attr('checked')) {
if (first == "") {
first = $(this).attr('value');
}
else if (second == "") {
second = $(this).attr('value');
}
}
else {
if (second == $(this).attr('value')) {
second = "";
}
else if (first == $(this).attr('value')) {
first = second;
second = "";
}
}
});
$('#btn').click(function () {
alert(first);
alert(second);
});
});
I hope that it will be helpful.
UPDATE [IMPORTANT]:
I have noticed that my previous code was incomplete, for example, if you check a1, then a2, then a3, then uncheck a2; my code was not recognising a3 as second.
Here is the complete solution of your updated problem. I used array this time.
The complete HTML:
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
The complete Javascript:
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
have 2 javascript variables first and second. whenever a checkbox is checked check if first is null if so assign the checkbox id to it, if first is not null set second.
You could have a change listener and a hidden field. Every time the user selects a checkbox, you add the value. Like so (assuming #parent is the parent element of the boxes):
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
$('#hidden').val($('#hidden').val() + " " + $(this).val())
}
});
The value of the hidden field would then be something like a2 a3 a1...
This is if you want to process the information at the server side. You can then split the string at the server side and examine it. Of course you have to handle removal and adding of selections.
If you just want to process the values on the client, you can add it to an array:
var selected = [];
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
selected.push($(this).val());
}
});
Try -
$(document).ready(function(){
var checked_no = 0;
$('input[name="checkbox1"]').change(function(){
alert($('input[name="checkbox1"]').filter(':checked').length);
checked_no = $('input[name="checkbox1"]').filter(':checked').length;
// checked_no acts as a counter for no of checkboxes checked.
});
});
Here you have it, if you want something more sophisticated (e.g. to test when an option is unclicked) you have to do some extra work. Just test this html in your browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type = "text/javascript">
var checkboxClicks = new Array(2);
function updateClickOrder(checkbox) {
if (checkbox.checked) {
if (checkboxClicks[0] ==null) {
checkboxClicks[0] = checkbox.value;
} else if (checkboxClicks[1] ==null) {
checkboxClicks[1] = checkbox.value;
}
}
document.forms[0].clickOrder.value = checkboxClicks[0] + ", " + checkboxClicks[1];
alert(document.forms[0].clickOrder.value);
//alert("Clicked " + checkbox.value);
}
</script>
</head>
<body>
<form name="testCheckboxClickOrder">
<input name="checkbox1" type="checkbox" value="a1" onchange="updateClickOrder(this);"> Option 1
<input name="checkbox1" type="checkbox" value="a2" onchange="updateClickOrder(this);"> Option 2
<input name="checkbox1" type="checkbox" value="a3" onchange="updateClickOrder(this);"> Option 3
<input name="checkbox1" type="checkbox" value="a4" onchange="updateClickOrder(this);"> Option 4
<input type="hidden" name="clickOrder"/>
</form>
</body>
</html>
This is going to save the order in an array. If you deselect the position is removed. The script will attempt to find the element by its value and remove. If you select again the value is added.
<input type="checkbox" value="v1" />
<input type="checkbox" value="v2" />
<input type="checkbox" value="v3" />
<input type="checkbox" value="v4" />
<textarea id="result"></textarea>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var userInput = [];
var c = 0;
$("input[type=checkbox]").click(function()
{
if ($(this).attr("checked"))
{
userInput[c] = $(this).val();
++c;
}
else
{
var i = parseInt(userInput.join().indexOf($(this).val())) - 2;
userInput.splice(i, 1);
}
});
$("textarea").click(function()
{
$(this).val("");
for (var i in userInput)
{
$(this).val($(this).val() + " " + userInput[i]);
}
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input name="checkbox1" type="checkbox" id="myCheck" value=" Option 1" onclick="myFunction('Option 1')" /> Option 1
<input name="checkbox1" type="checkbox" id="myCheck2" value=" Option 2" onclick="myFunction2('Option 2')" /> Option 2
<input name="checkbox1" type="checkbox" id="myCheck3" value=" Option 3" onclick="myFunction3('Option 3')" /> Option 3
<input name="checkbox1" type="checkbox" id="myCheck4" value=" Option 4" onclick="myFunction4('Option 4')" /> Option 4
<p id="getValues"></p>
</body>
<script>
var array = [];
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function myFunction(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction2(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck2");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction3(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck3");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction4(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck4");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function getValues()
{
$("#getValues").html(array.join("<br>"));
}
</script>
</html>

Categories

Resources