increase and decrease value using a radio button - javascript

I am developing an eCommerce system.
Let say if user has total of 1200 right.
If he chooses fast delivery options
40 should be added to total that means at the end amount should be changed from 1200 to 1240.
I have a developed a kind of application for that.
I don't know what but the value is not increment. Don't know what but I need a solution,
Here is my code:
<label><input type="radio" name="optradio" id="target">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="savevalue" style="visibility:hidden"></div>
<label><input type="radio" name="optradio" id="target2">
<span class="label label-success">Regular Delivery</span></label>
My Javascript code:
$('#target').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (savevalue==null || savevalue=="")
{
output = output*1 + 40;
savevalue = output;
$('#output').html(function(i, val) { return output});
$('#savevalue').html(function(i, val) { return savevalue});
}
});
$('#target2').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (output==savevalue)
{
output = output*1 - 40;
$('#output').html(function(i, val) { return output });
}
});

Try this :
HTML :
<p id="price">100</p>
<input type="radio" name="delivery" id="delivery1" value="normal" checked> Normal <br>
<input type="radio" name="delivery" id="delivery2" value="fast"> Fast
Js:
$(document).ready(function(){
$('#delivery1,#delivery2').change(function(){
price = $('#price').text();
if($('#delivery2').is(':checked')) {
price = parseInt(price) + 40;
} else {
price = parseInt(price) - 40;
}
$('#price').text(price);
});
});

can you check on my fiddle https://jsfiddle.net/3422ntLh/.
In my solution, check the html code.
<label>
<input type="radio" name="delivery" id="target" speed="fast">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="original" value="10" style="visibility:hidden"></div>
<label>
<input type="radio" name="delivery" id="target2" speed="normal">
<span class="label label-success">Regular Delivery</span></label>
I saved the value of the good in $('#original).
This is my JS code:
$('input:radio[name="delivery"]').change(function() {
alert($('#original').attr('value'));
$('#output').html($('#original_cost').attr('value'));
if ($(this).attr('speed') == 'fast') {
var extra_shipping_fee = 40;
var current_price = parseInt($('#original').attr('value'));
var new_price = current_price + extra_shipping_fee;
$('#output').html(new_price);
} else {
$('#output').html($('#original').attr('value'));
}
})
The code is not refine, but it will give you some insights on how to continue

Related

How get the sum of all the checkbox values of checked items

let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.
This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>
You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.
When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>
Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>

Change prices based on checkbox click

im currently looking for help in this matter.
The problem here is that instead of doing the checkbox value + the previous value it is adding it all together like placing "10" and after other checkbox click it adds the value to it and does not count it like "1020" instead of doing 10+20
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
input.value += input.value + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Check if repeatedly click on checkbox should be handled also on uncheck score should reduced.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
total = parseInt(document.getElementById("valor").value);
if(isNaN(total)){
total = 0;
}
if($(this).prop('checked')){
total = total + parseInt($(this).val());
} else {
total = total - parseInt($(this).val());
};
var input = document.getElementById("valor");
input.value = total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
The code
input.value += input.value + total;
means (since input.value is a String), concatenate input.value with total after making sure total is a String. Don't use the += and be sure to use parseInt() on anything that you want to be a number.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
/*
* You don't need +=
* You do need to parseInt
* You need to make sure to handle empty String ""
*/
input.value = (parseInt(input.value, 10) || 0) + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label>
<br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Please correct me, if I don't quite understand your problem, but shouldn't you just have to change input.value += input.value + total; to input.value = total; for the required result?
As you are using jQuery and I love to user reduce method I can advice you this solution
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = $('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
return pre + parseInt($(post).val());
}, 0);
$('#valor').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
If your value is always a number you can use value / 1 to convert number string into numeric type. This only if you are SURE that the number will be always a number and not a string containing number, eg. 11.jpg is not valid.
This is a performance test for your case:
https://jsperf.com/parseint-versus-divide-by-one/1
So you can rewrite the code as:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total =
$('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
var val = $(post).val() / 1;
return pre + (val ? val : 0);
}, 0);
$('#valor').val(total);
});
});

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

Function to set textarea value - additional runs through append data instead of replace it

I have a textarea, whose value I want to set with a function. When I first click the button to set the value, the value populates correctly.
If I then click the button to set the value again, using a different option from the list of radio buttons, the value in the textarea is not cleared and replaced with the new data - data resultiing from the logic in the JS code is appended to the data in the textarea, instead of replacing what is already there.
I have tried to clear the textarea value with:
document.getElementById("output").value = '';
But that doesn't clear it.
HTML:
<label class="radio-inline">
<input type="radio" name="myArray" id="radioActivity" value="valActivity"> Activity
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioFlags" value="arrFlags"> Flags
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioFood" value="arrFood"> Food
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioNature" value="arrNature"> Nature
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioObjects" value="arrObjects"> Objects
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioPeople" value="arrPeople"> People
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioLetters" value="arrLetters"> Letters
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioSymbols" value="arrSymbols"> Symbols
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioTravel" value="arrTravel"> Travel
</label>
<input type="text" class="form-control" id="itemSet" value="10" />
<button id="rdio"> Check Radio </button>
<textarea id="output" class="form-control" style="width:95%; height:500px; margin-top:20px;"></textarea>
JS:
var myCols = 2;
var arrActivity = ["alien monster","man in business suit levitating","fencer","horse racing","skier","snowboarder","golfer","surfer","rowboat","swimmer"];
var arrFlags = ["ascension","andorra","the united arab emirates","afghanistan","antigua and barbuda","anguilla","albania","armenia","angola","antarctica"];
var arrFood = ["grapes","melon","watermelon","tangerine","lemon","banana","pineapple","red apple","green apple","pear"];
var arrNature = ["see-no-evil monkey","hear-no-evil monkey","speak-no-evil monkey","splashing sweat symbol","dash symbol","monkey face","monkey","gorilla","dog face","dog"];
var arrObjects = ["skull and crossbones","love letter","bomb","hole","shopping bags","prayer beads","gem stone","hocho","amphora","world map"];
var arrPeople = ["grinning face","grinning face with smiling eyes","face with tears of joy","rolling on the floor laughing","smiling face with open mouth","smiling face with open mouth and smiling eyes","smiling face with open mouth and cold sweat","smiling face with open mouth and tightly-closed eyes","winking face","smiling face with smiling eyes"];
var arrLetters = ["letter a","letter b","letter c","letter d","letter e","letter f","letter g","letter h","letter i","letter j"];
var arrSymbols = ["eye in speech bubble","heart with arrow","heavy black heart","beating heart","broken heart","two hearts","sparkling heart","growing heart","blue heart","green heart"];
var arrTravel = ["racing car","racing motorcycle","silhouette of japan","snow capped mountain","mountain","volcano","mount fuji","camping","beach with umbrella","desert"];
var arrNew = [];
function boom()
{
if (document.getElementById("radioActivity").checked) {
y = arrActivity;
} else if(document.getElementById("radioFlags").checked) {
y = arrFlags;
} else if (document.getElementById("radioFood").checked) {
y = arrFood;
} else if (document.getElementById("radioNature").checked) {
y = arrNature;
} else if (document.getElementById("radioObjects").checked) {
y = arrObjects;
} else if (document.getElementById("radioPeople").checked) {
y = arrPeople;
} else if (document.getElementById("radioLetters").checked) {
y = arrLetters;
} else if (document.getElementById("radioSymbols").checked) {
y = arrSymbols;
} else if (document.getElementById("radioTravel").checked) {
y = arrTravel;
}
for (var i = 0; i < y.length; i+=myCols) {
arrNew.push(
y.slice(i, i+myCols)
);
}
// attempts to clear the output...
// op = '';
document.getElementById("output").value = '';
// set the textarea output
op = JSON.stringify(arrNew, null, 4);
document.getElementById('output').value = op;
}
var z = document.getElementById('rdio');
z.addEventListener("click", boom);
Codepen to show issue:
https://codepen.io/paperknees/pen/JrgNzp
arrNew should be declared as an empty array inside the function call every time.
function boom() {
var arrNew = [];
...

Javascript taking .innerHTML on indexOf checked

I have a variable named 'options'. Whenever a user checks one of the checkboxes, I need 'options' to populate the string with the .innerHTML for each checked checkbox. For example, when Instagram and Google+ are checked, 'options' would = Instagram, Google+.
html:
<section id="extra-features">
<div class="span3">
<label class="checkbox" for="Checkbox1">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> LinkedIn
</label>
</div>
<div class="span3">
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Pinterest
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> FourSquare
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Tumblr
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Advertising
</label>
</div>
</section>
<div class="card-charge-info">
Your card will be charged $<span id="payment-total">0</span> now, and your subscription will bill $<span id="payment-rebill">0</span> every month thereafter. You can cancel or change plans anytime.
</div>
javascript:
var price = 0,
additional = 0,
options = "",
inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.parentNode.className.split(" ").indexOf("checked") > -1 ? 1 : -1);
additional += add
total.innerHTML = price + additional;
if (price == select.options[2].value) {
total2.innerHTML = 0;
}
else {
total2.innerHTML = price + additional;
}
}
}
JSFiddle: http://jsfiddle.net/rynslmns/LQpHQ/
I would recommend tabulating the information each time they change a check state. What you're doing now is problematic; currently you start at 0, but end up being in the negative (total price) quickly by checking and unchecking a couple of options.
Also, options, as a string, will become difficult to keep up with. I'd probbaly make that an array that you can add/remove from (but if you tabulate at the end, there's no worrying).
For example:
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
// Perform the summing
// Though I'm not sure where total is coming from, but you can work that out.
// And for now I have it alerting the options, but you can do whatever you'd like with that.
function sumItUp(){
var ttl = 0, additional = 0, options = [];
for (var i = 0; i < inputs.length; i++){
if (inputs[i].checked){
options.push(inputs[i].parentNode.textContent.trim());
var n = new Number(inputs[i].value);
if (!isNaN(n)) additional += n;
}
}
total.innerHTML = ttl.toFixed(2);
total2.innerHTML = (ttl + additional).toFixed(2);
alert('Options:\n\n' + options.join(', '));
}
// bind events to sum it on every change
for (var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('change', sumItUp);
}
// Polyfill for trim()
if (!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
jsFiddle
You won't be able to use .innerHTML to get the text of the checkbox since it doesn't contain any text. You'll want to use .nextSibling instead. Something like this should work:
var price = 0,
additional = 0,
options = "",
inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var text = this.nextSibling.nodeValue;
if(options.indexOf(text) != -1) {
options += text + ',';
}
}
}
Of course you'd also want to handle when a checkbox is unselected as well.

Categories