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

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>

Related

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

How to get last clicked radio value using jquery?

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

javascript change and send multiple checkbox values

H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>

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

increase and decrease value using a radio button

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

Categories