How to get last clicked radio value using jquery? - javascript

I am trying to sum or subtract price into total price as you can see in below working script. Following script is working properly but I want to minus previous clicked radio price from total price.
Suppose If i clicked on Wrap which price is 3 so total price become 8. But when i clicked on any other radio button the Wrap price should minus from total. For that task i tried a lot and looking for solution. Is there any way to store previous clicked price? I would like to thanks if someone guide me.
$('.SECOND_POP_PRICE').on('click', function() {
if ($(this).is(':checked')) {
var PRICE_Product_ID = $(this).parent().attr('data-product_id');
var SECOND_SECTION_PRICE = parseFloat($(this).parent().attr('data-second_section_price'));
var SECOND_SECTION_POP_PRICE = parseFloat($('#pop_price_' + PRICE_Product_ID).text());
if (SECOND_SECTION_PRICE != 0) {
var SECOND_SECTION_UPDATED_PRICE = +SECOND_SECTION_PRICE + +SECOND_SECTION_POP_PRICE;
$('#pop_price_' + PRICE_Product_ID).text(SECOND_SECTION_UPDATED_PRICE);
}
} // if checkbox is checked
/* if($(this).prop('checked')==false){ */
else {
var PRICE_Product_ID = $(this).parent().attr('data-product_id');
var SECOND_SECTION_PRICE = parseFloat($(this).parent().attr('data-second_section_price'));
var SECOND_SECTION_POP_PRICE = parseFloat($('#pop_price_' + PRICE_Product_ID).text());
if (SECOND_SECTION_PRICE != 0) {
var SECOND_SECTION_UPDATED_PRICE = parseFloat(SECOND_SECTION_POP_PRICE - SECOND_SECTION_PRICE);
$('#pop_price_' + PRICE_Product_ID).text(SECOND_SECTION_UPDATED_PRICE);
}
} // if checkbox is un-checked
}); /* END PRICE OF SECOND SECTION 1 */
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<small class="pop_price"><span id="pop_price_2">5</span> AED</small>
<br />
<label data-product_id="2" data-second_section_price="3.00">
<input type="radio" class=" toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Wrap">
Wrap (3.00 AED)</label>
<label data-product_id="2" data-second_section_price="4.00">
<input type="radio" class=" toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Roll">
Roll (4.00 AED)</label>
<label data-product_id="2" data-second_section_price="5.00">
<input type="radio" class="hide_section_3 toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Open">
Open (5.00 AED)</label>

Don't add the clicked radio button to the total. Add it to the base price, which is stored somewhere other than the text of the span that you display the total in. In my code below I put it in the data-price attribute of the span.
There's also no need for the if, since you can't uncheck a radio button.
$('.SECOND_POP_PRICE').on('click', function() {
var PRICE_Product_ID = $(this).parent().attr('data-product_id');
var SECOND_SECTION_PRICE = parseFloat($(this).parent().attr('data-second_section_price'));
var SECOND_SECTION_POP_PRICE = parseFloat($('#pop_price_' + PRICE_Product_ID).data("price"));
if (SECOND_SECTION_PRICE != 0) {
var SECOND_SECTION_UPDATED_PRICE = +SECOND_SECTION_PRICE + +SECOND_SECTION_POP_PRICE;
$('#pop_price_' + PRICE_Product_ID).text(SECOND_SECTION_UPDATED_PRICE);
}
}); /* END PRICE OF SECOND SECTION 1 */
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<small class="pop_price"><span id="pop_price_2" data-price="5.00">5</span> AED</small>
<br />
<label data-product_id="2" data-second_section_price="3.00">
<input type="radio" class=" toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Wrap">
Wrap (3.00 AED)</label>
<label data-product_id="2" data-second_section_price="4.00">
<input type="radio" class=" toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Roll">
Roll (4.00 AED)</label>
<label data-product_id="2" data-second_section_price="5.00">
<input type="radio" class="hide_section_3 toggle_section_3 SECOND_POP_PRICE" name="section_two" value="Open">
Open (5.00 AED)</label>

// here that refers to the context which is you can use to store the last value, you need to find out that context
$('.SECOND_POP_PRICE').on('change',function(event,that){
var updatedValue = that.lastValue - this.value;
$('#pop_price_'+PRICE_Product_ID).text(updatedValue);
that.lastValue = updatedValue
})

Related

How to change the value of a previous check box that has been selected in JQuery?

Here is what I'm trying to do.
I have the ability to create a form when there is an option to create one in Javascript.
Here is an option to add an address:
<i class="fas fa-plus-circle"></i> <span class="newUrlText">add new address
Here is the form in question:
<input type="text" class="form-control" id="new-address-1-%ID%" name="new-address-1-%ID%" placeholder="Address Line 1">
<input type="text" class="form-control" id="new-address-2-%ID%" name="new-address-2-%ID%"
placeholder="Address Line 2">
<label for="message" class="control-label"><span class="billable-text"><?php _e('Primary Address'); ?></span></label>
<label class="switch" for="primary-%ID%" style="margin-left: 10px;top: 10px;">
<input type="checkbox" class="primary-%ID%" name="primary-%ID%" id="primary-%ID%" />
<div class="slider round gray"></div>
</label>
Here is the javascript that generates the form:
<script language="javascript">
var newAddressIndex = 1;
var addressarray = [];
function addNewAddress() {
var container = getElement("addressContainer");
addressarray.push(newAddressIndex);
var htmlAddress = '<?php echo addslashes(App_String::stripBreaksTabsMultipleWhitespace($newAddress)); ?>';
htmlAddress = htmlAddress.replace(/%ID%/g, newAddressIndex);
var node = document.createElement("div");
node.innerHTML = htmlAddress;
container.appendChild(node);
$('#newAddressCount_'+newAssetIndex).val(newAssetIndex);
++newAddressIndex;
test(addressarray);
}
What I'm trying to do is the following:
If the user selects the checkbox and then decides to select the next checkbox, I would like to change the previous checkbox from selected to no selected.
How would I go about doing that?
Thank you
I found a solution:
What I did was, that I created a function to get the current value of the checkboxes like this:
getAddrValue(addressarray);
Then within the function the follwoing:
function getAddrValue (addressarray) {
$('#primary-'+index).change(function() {
var checked = this.checked ? 1 : 0;
prevCheckbox = index-1;
if (checked == 1) {
if (document.getElementById('primary-'+prevCheckbox) !== null ) {
let inputs = document.getElementById('primary-'+prevCheckbox);
inputs.checked = false;
}
}
});
}

How can I save a total score in localstorage each time a checkbox is checked

I've built a small game using checkboxes with images. When the user comes across the item in the picture they select the checkbox and the message changes on screen. Because this is a tourist guide website and game, the user will leave the page to look at other pages, selecting the pictures as they come across the item. Therefore I needed to save the checked boxes in localstorage so that the data persists. I have some javascript that dsave the checked boxes.
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened.
My javascript for calculating the total and storing the checkboxes is below.
$('.dp-spotter-switch input[type="checkbox"]').click(function () {
if (!$(this).is(':checked')) {
$(this).parent('.dp-spotter-switch').removeClass('spotter-scale');
} else {
$(this).parent('.dp-spotter-switch').addClass('spotter-scale');
}
});
function showDiv() {
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
(function () {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function () {
localStorage.setItem(storageId, this.checked);
});
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dp-spotter-container">
<div class="dp-top-paragraph">
<p>Some text</p>
<p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p>
<div id="getScoreLabel" style="display:none; text-align: center;">
<div class="dp-your-score-text" id="getScore">Your Score</div>
<input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/>
</div>
</div>
<br/>
<br/>
<!-- Spotter 1 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1">
<span class="dp-spotter-slider"></span>
<span class="dp-spotter-text-label">Item 1- 3 Points</span>
</label>
</div>
<!-- Spotter 2 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 2 - 3 Points</p>
</label>
</div>
<!-- Spotter 3 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">ITem 3 - 5 Points</p>
</label>
</div>
<!-- Spotter 4 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 4 - 10 Points</p>
</label>
</div>
Get Your Score
</div>
I'm looking for a way to add to the existing function for the checkboxes if possible.
Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action.
Since you're using jQuery, I've gone ahead and provided a jQuery solution:
Used .attr() to set the checkbox based on local storage
Called totalIt when showing showDiv
If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function
Demo
https://repl.it/#AnonymousSB/SO53500148
Solution
function showDiv() {
totalIt();
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
function setupBox(box) {
var storageId = box.attr("store");
var oldVal = localStorage.getItem(storageId);
box.attr('checked', oldVal === "true" ? true : false)
box.change(function() {
localStorage.setItem(storageId, this.checked);
});
}
$(document).ready(function () {
$( "input[type='checkbox'][store]" ).each(function( index ) {
setupBox($( this ));
});
})
You can open Chrome Dev Tools, go to Application, and see your local storage

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>

How to retrieve data from localStorage in JS from multiple radio buttons after page refresh?

This is my first question so.. be gentle and I'm sorry if there is some mistake. Thank you.
I have groups of radio buttons and this is the HTML:
<div class="radio">
<label for="a_a">
<input type="radio" name="some_name" id="a_a" value="some_value">
</label>
<label for="a_b">
<input type="radio" name="some_name" id="a_b" value="some_value">
</label>
</div>
<div class="radio">
<label for="b_b">
<input type="radio" name="some_name" id="b_b" value="some_value">
</label>
<label for="b_c">
<input type="radio" name="some_name" id="b_c" value="some_value">
</label>
</div>
and this is the JS:
$(".radio label").on('click', function (e) {
var input_id = $(this).children().attr('id');
var input_value = $(this).children().attr('value');
localStorage.setItem(input_value, input_id);
});
var itemID = localStorage.getItem("option");
if (itemID !== null) {
$("input[id=\"" + itemID + "\"]").click();
};
This works well, but the problem is that I'm getting the id only of the last clicked radio button and the question is: How to get the id's from both groups of radio buttons. Please, be aware that there might be more than 2 groups of radio buttons.
Thank you.
Are you looking for something like this? https://jsfiddle.net/sxh0n7d1/15/
what do you want to do with the values?
window.onbeforeunload = function() {
$('input[type="radio"]').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
}
window.onload = function() {
$('input[type="radio"]').each(function(){
var id = $(this).attr('id');
var getValue = localStorage.getItem(id);
alert("value = "+getValue+" id = "+id);
});
}

Cannot update score

I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];

Categories