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

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>

Related

how to calculate the total of two incremented values from two different loops?

I have a function that calculates sum of input values. In this form I have checkboxes and number type inputs. I'm able to make this function work with either only checkboxes or textboxes but not both at the same time. The two input types enter in conflict. It's probably very trivial but I can't seem to figure it out. Any help?
js
$(document).on("change", ".calculate", function () {
calculateTotal();
});
function calculateTotal() {
//input type number
var textboxsum = 0;
//input type checkbox
var addonsum = 0;
//iterate through each input
$(".calculate").each(function () {
//get input type
var type = this.getAttribute("data-type");
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === "room") {
//add amount $35 per room
var amount = parseFloat(this.value * 35);
} else if (type === "addon") {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat(this.value * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() roundoff to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
there are few issues in the code, and you can use parseInt instead of parseFloat
$('.calculate').change(function() {
let amount = 0;
$(".calculate").each(function() {
const type = this.getAttribute('data-type');
if (!isNaN(this.value) && this.value.length !== 0) {
if (type === 'room') {
//add amount $35 per room
amount = parseInt(this.value, 10) * 35;
} else if (type === 'addon' && this.checked) {
amount += parseInt(this.value, 10) * 10;
}
}
});
$(".total_amount").html(amount.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount">0</span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
You have to declare var amount = 0; at top inside .each(). The reason you are getting NaN when type is not room then it will not execute code from if(type==='room') where you have declared amount and in end you have used textboxsum += parseFloat(amount);, so here amount will return undefined & textboxsum will become NaN.
Try it below.
$(document).on('change', '.calculate', function() {
calculateTotal();
});
function calculateTotal() {
//from input type number
var textboxsum = 0;
//from input type checkbox
var addonsum = 0;
//iterate through each textboxes and add the values
$(".calculate").each(function() {
//get input type
var type = this.getAttribute('data-type');
// declare amount variable here
var amount = 0; // <-- Change
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === 'room') {
//add amount $35 per room
// do not declare variable here. just use it
amount = parseFloat((this.value) * 35);
} else
if (type === 'addon') {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat((this.value) * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() method will roundoff the final sum to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">

summing up in js with 2 options checked

i have this code in html
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
and then the js
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
i need the first two checked checkboxes to sum up from start when page loads
and after the behavior of js to get me to 0 or to total of checkboxes when checking respectively unchecking
You could add an eventlistener to the page loading and just select the options using querySelectorAll("input[type=checkbox]") which selects all checkboxes, iterarate over them and sum them up.
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
window.addEventListener("load", function() {
var options = document.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < options.length; i++) {
const o = options[i];
if (o.checked) total += Number(o.value);
}
document.getElementById("total").innerHTML = total;
}, false);
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
Use a class:
<input type="checkbox" value="12" id="logo" class='summary' checked>
<input type="checkbox" value="19" id="bc" class='summary' checked>
<input type="checkbox" value="200" id="first" class='summary'>
<input type="checkbox" value="250" id="second" class='summary'>
document.addEventListener('DOMContentLoaded', function() {
var summerizers = document.querySelectorAll('.summary'),
counter = document.getElementById('counter');
for (var i = 0, c = summerizers.length; i < c; i++) {
summerizers[i].addEventListener('change', count);
}
count();
function count() {
var total = 0;
for (var i = 0, c = summerizers.length; i < c; i++) {
if (summerizers[i].checked) {
total += parseInt(summerizers[i].value, 10);
}
}
counter.value = total;
}
});
https://jsfiddle.net/r1khjrsd/
You can call the function, then recall the function onchange event. Don't need to pass this as parameter
function calculate() {
total = 0;
elements = document.getElementsByTagName('input');
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
total += Number(elements[i].value);
}
}
document.getElementById('total').innerHTML = total;
}
calculate();
<input type="checkbox" value="12" id="logo" checked onchange="calculate();">
<input type="checkbox" value="19" id="bc" checked onchange="calculate();">
<input type="checkbox" value="200" id="first" onchange="calculate();">
<input type="checkbox" value="250" id="second" onchange="calculate();">
<p id="total"></p>
To achieve expected result, use initial flag checking initial page load and checkTotal function to checked boxes on initial load
Steps:
Function checkedTotal to check all checked checkboxes and call calculate function with boolean value start
If start is true, only add checked checkbox values and restrict else part in calculate functionenter code here
code sample - https://codepen.io/nagasai/pen/XEyqEd?editors=1111
var total = 0;
function calculate(option,start) {
if (option.checked) {
total += Number(option.value);
} else {
if(!start){
total -= Number(option.value);
}
}
document.getElementById("total").innerHTML = total;
}
function checkedTotal(){
var checkList = document.getElementsByTagName('input');
for(var i =0; i < checkList.length; i++){
calculate(checkList[i], true)
}
}
checkedTotal()
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>

How to use checkbox as radio button for calculate total

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);
}
});
});

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="" />

formulization in jquery using values

I m learning jquery a bit so i created this fiddle here http://jsfiddle.net/8FXFE/17/
this is my html code
<div class="textForm">
<input type="radio" name="txtNumber" value="100" checked="checked" />100
<input type="radio" name="txtNumber" value="200" />200
<input type="radio" name="txtNumber" value="500" />500
<input type="radio" name="txtNumber" value="1000" />1000
<input type="radio" name="txtNumber" value="10000" />10000
<input type="radio" name="txtNumber" value="other" />other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"
/>
</div>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ" checked="checked"
/>Space 1.
<br />
<input type="radio" name="txtSpace" value="SM" />Space 2.
<br />
</div>
<h3>Output:</h3>
this is css
#other_field {
display: none;
}
this is jquery
$(document).ready(function () {
console.log("parsed");
$("input[name='txtNumber'],input[name='txtSpace']").change(function () {
$("#output").text("Changed to "+$("input[name='txtNumber']:checked").val() + " " +$("input[name='txtSpace']:checked").val() + " +++++SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER++++++"
);
});
});
$(':radio').on('change', function () {
$('#other_field')[$(this).val() === 'other' ? 'show' : 'hide']();
});
$('#other_field').on('blur', function () {
var val = $(this).val();
if(isNaN(val)) {
alert('only numbers are allowed..');
}
else if(parseInt(val, 10) % 10 > 0) {
alert('only multiples of 10..');
}
});
How can i achieve actual output those shown in capital letters inside +++++++++++
SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER
Also How can i add dynamic value of hidden other_field (if selected)
var value = $("input[name='txtNumber']:checked").val();
if(value == "other"){
value = parseInt($("#other_field").val());
}
if(!value || isNaN(value)) value = 0;
var type = $("input[name='txtSpace']:checked").val();
var fixedMultiplier;
switch(type){
case "RJ": fixedMultiplier = 100; break;
case "SM": fixedMultiplier = 50; break;
default: fixedMultiplier = 1; break;
}
var computedValue = value * fixedMultiplier;
$("#output").text("Changed to "+ value + " " + type + " (" + computedValue + ")");
http://jsfiddle.net/8FXFE/19/
Maybe you should also add a handler to the textfield to update output on keyup.

Categories

Resources