Apply to everyone with checkbox - javascript

I record meals in this way, as I show in the image:
I created the Apply to All button, which is to fill the remaining days of the month with the same data after completing the 1st of the month. For example:
I pre-pack the day 1:
By clicking the Apply to All button fill the remaining days in the same way:
Code:
<input type='button' id='elemento' value='Aplicar a Todos' />
<td bgcolor='$color' data-semana=''><font size='2px'/>
<input id='firstCB{$year}{$month}{$day}' type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day'>$year-$month-$day <br />
<div>
<input type='checkbox' class='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço'>Peq. Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' />
<br />
</div>
<div>
<input type='checkbox' class='checkbox1' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço'>Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd'/>
<br />
</div>
</td>
Javascript:
$('#elemento').on('click', function(){
var inputs = [...document.querySelectorAll("[type='checkbox']")];
if(inputs == 'checked'){ // condição
$('.checkbox').prop('checked', true);
$('.checkbox1').prop('checked', true);
}
});
I wanted you to select all the checkboxes on every day as on day 1 and also fill in the inputs with the same value as day 1.
As I have the condition does not select any checkbox when clicking the Apply to all button.

I know you are using JQuery, but heres an option in vanilla JS. Talvez te servia melhor. Portugal Ale!
const dayChecks = document.querySelectorAll('.day input[type="checkbox"]');
const dayInputs = document.querySelectorAll('.day input[type="number"]');
const btn = document.querySelector('#click');
btn.addEventListener('click', () => {
dayChecks.forEach( input => { // Handles checkboxes
if(input.checked){
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="checkbox"]').setAttribute('checked', 'checked');
});
}
});
dayInputs.forEach( input => { // Handles Inputs
if(input.value != ''){
const value = input.value;
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="number"]').value = value;
});
}
});
});
.week {
display: flex;
flex-direction: row;
}
.day{
padding: 20px;
}
<button id='click'>Apply to All</button>
<div class="week">
<div class="day">
<h2>Primeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Segundo Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Terçeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
</div>

If you want an elegant JQuery implementation try this:
$(document).ready(function(){
// used the first checkbox (input with the date class) to select each data column for entering data
// this is the column you want replicated on other columns
$('.date').change(function() {
// inactivate every other column that is not this column
$('.date').not($(this)).prop('checked', false).parents('td').removeClass('active');
// show that this is the currently selected column
$(this).parents('td').toggleClass('active');
});
// click handler for 'apply to all' button
$('#elemento').click(function() {
var checkboxstate = {}; // object to store all the checkbox state in the current column
var numberstate = {}; // object to store content of all text input in the current column
// for each input element in the active column
$.each($('.active').find('input'), function(key, element){
if($(this).prop('type') == 'checkbox') {
// collect all checkbox state
checkboxstate[element.name] = $(this).prop('checked');
} else {
// collect all input text content
numberstate[element.name] = $(this).val();
}
});
// for each checkbox or number
$.each($('.checkbox, .number'), function(key, element) {
// store these variables beforehand so you don't need to test for them in the inner each statement
// for checkboxes
var target = checkboxstate;
var type = 'checkbox';
var property = 'checked';
// for number elements
if($(this).is('.number')) {
target = numberstate;
type = 'number';
property = 'value';
}
// assign object properties to dom elements with same type and name properties as that of the object property
$.each(target, function(key_1, element_1) {
if($(element).prop('type') == type && $(element).prop('name') == key_1) {
$(element).prop(property, element_1);
}
});
});
return false;
});
});
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js"></script>
<title>My test doc</title>
<style>
table {
border-collapse: collapse;
}
.active {
background-color: #00ff00;
}
input {
margin-bottom: 5px;
}
.checkbox-div {
float: left;
}
.number-div {
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<h3>welcome</h3>
<form method="GET" action="#">
<table style="border-collapse: collapse">
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
</table>
<input type='button' id='elemento' value='Aplicar a Todos' />
</form>
</body>
</html>
Also see the Fiddle sample here
Here, each column is represented by a td element. I used the first checkbox with the date class to select the column we want other columns to replicate.
Also, the checkbox and number inputs are loosed coupled - that is, a checkbox can be unchecked with the corresponding number input filled and this will still be replicated on other columns.
Three columns were used for brevity. You can create as many columns as you want and the jQuery script will still run seamlessly.

You can apply classes to each checkbox and select all checkbox on click of Apply to All button
<input type="checkbox" class="Almoco" />
$('#elemento').on('click', function(){
if(check for your condition if you need to apply check for all checkboxes)
{
$('.Almoco').prop('checked', true);
}
//Similiarily check for other checkboxes
});

Your variable inputs is a collection of inputs, therefore you have to check the state of each input in a forEach or a for loop.
Same for other inputs that you want to modify the state.
Code:
$('#elemento').on('click', function(){
var inputs = $('td > input');
inputs.each(function(index, element){
if(element.checked) {
var children = $(element).parent().find('input[type="checkbox"]');
children.each(function(i, child){
$(child).prop('checked', true);
});
}
});
});

I was able to solve the problem of applying to everyone in the following way:
$('#elemento').click(function() {
var checkedValues = Array(8).fill(false);
var textValues = Array(7).fill('');
var checkedStep = 0;
var textStep = 0;
$('tr').find('input[type="checkbox"]').each(function(index, value){
if(index < 8){
checkedValues[index] = $(this).prop("checked");
}else{
if(checkedStep == 8){
checkedStep = 0;
}
$(this).prop('checked', checkedValues[checkedStep++]);
}
});
$('tr').find('input[type="number"]').each(function(index, value){
if(index < 7){
textValues[index] = $(this).val();
}else{
if(textStep == 7){
textStep = 0;
}
$(this).val(textValues[textStep++]);
}
});
});

Related

Event listeners for both radio buttons and text input

I have a group of radio buttons and a text input field:
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
And I wanna the result of final price calculated by Price * Discount and updating the <p id="resultToast"> </p>.
So I did
const radios = document.querySelector('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
From the console, the radios.value not updated correctly after clicking the radio buttons. What I did wrong?
Just change:
const radios = document.querySelector('input[name="discount"]:checked');
To:
const radios = document.querySelectorAll('input[name="discount"]:checked');
See working snippet:
const radios = document.querySelectorAll('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
Reason for this is because you stored the initial
document.querySelector('input[name="discount"]:checked');
value as radios. Now that we look for all, it changes accordingly.
You are referring to a constant you defined at the beginning of your script. This will always give you the same radio button value (the one being checked at the beginning). Do something like
let discount=document.querySelector("input[name=discount]:checked").value
within your event handler function to get the current value of the radio button group.
You could also declutter(=shorten) your code a bit and make it reusable for multiple input sections that way, see below:
function qs(sel,el){return (el||document).querySelector(sel);}
function makeInteractive(frmsel){
const frm=qs(frmsel),
prc=qs("[name=price]",frm),
res=qs(".result",frm);
frm.onchange=calc;
frm.oninput= calc;
function calc(){
res.textContent=
(prc.value * qs("[type=radio]:checked",frm).value)
.toFixed(2);
}
}
makeInteractive("#frm1");
makeInteractive("#frm2");
<form id="frm1">
the first item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
<form id="frm2">
the second item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>

How to create CheckBox onClick Event in asp.net MVC

I'm accessing the data for the CheckBoxes from the database, now I want to display the form for each and every checkbox if it's checked. How to achieve this?
My form design -
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" /> #item.type<br />
<div class="col-sm-12" style="display:none;" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
I want to display the price input when checkbox is checked.
My back-end code -
ViewBag.RoomTypes = db.RoomTypes.ToList();
My code's generating this output -
My code's generating this output
You can easily do that with css. Add chkshowhide css class to your input and div and add css as per code. Your code will be as below.
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" class="chkshowhide"/> #item.type<br />
<div class="col-sm-12 chkshowhide" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
css.
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
You can test sample here.
function saveData() {
$('input.chkshowhide:checked').each(function() {
var chkValue = $(this).val();
var divId = this.id.replace("chk", "Price");
var priceValue = $('#' + divId).find('input').val();
console.log('chkValue=' + chkValue + ", priceValue=" + priceValue);
// Write your save code here
});
}
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="checkbox" id="chk_1" name="RoomTypes" value="1" class="chkshowhide"> 1<br />
<div class="col-sm-12 chkshowhide" id="Price_1">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_2" name="RoomTypes" value="2" class="chkshowhide"> 2<br />
<div class="col-sm-12 chkshowhide" id="Price_2">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_3" name="RoomTypes" value="3" class="chkshowhide"> 3<br />
<div class="col-sm-12 chkshowhide" id="Price_3">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="button" value="Save" onclick="saveData();" />

Display all selected items from checkboxes

I am using this codepen as a basis.
HTML
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
jQuery
$("input").on("click", function() {
$("#log").html($("input:checked").val() + "");
});
I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.
The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.
How can this be done?
$( "input" ).on( "click", function(e) {
if(e.currentTarget.checked){
var div = document.createElement("p");
div.id=e.target.value+"1";
div.innerHTML=e.target.value;
var tar=document.getElementById("log");
tar.appendChild(div);
} else {
var tag = document.getElementById(e.target.value+"1");
tag.parentNode.removeChild(tag);
}
});
You can try this its working.
Now when you click orange displayed and unchecked removed.
You need to make a couple of changes
If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.
Maintain an attribute wasChecked to toggle the checked property.
You need to iterate the checked boxes and then get their values.
Demo
$("input").on("click", function(e) {
var val = [];
var wasChecked = $(this).attr( "wasChecked" ) == "true";
if ( wasChecked )
{
$(this).prop( "checked", false );
}
else
{
$(this).prop( "checked", true );
}
$(this).attr( "wasChecked", $(this).prop( "checked") );
$("input:checked").each( function(){
val.push( $(this).val() );
});
$("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="radio" name="fruit1" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit2" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit3" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.
you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.
$( "input" ).on( "click", function() {
var html = "";
$( "input:checked" ).each(function() {
// "this" in this context is the jQuery element in this position in the list
html += $(this).val() + "";
}
$( "#log" ).html(html);
});
$( ":checkbox" ).on('change',function(){
var li_id = 'li_'+$(this).attr('id');
if(this.checked){
$('#list').append("<li id="+li_id+">"+$(this).val()+"</li>")
}else{
$('#'+li_id).remove();
}
})
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<ul id='list'>
</ul>
This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.
Now you have an array. So, maybe you need something like this?
$( "input" ).on( "click", function() {
var selectedItems = $( "input:checked" );
var results = "";
for(var i = 0; i < selectedItems.length; i++){
if(i > 0) results += ", ";
results += selectedItems[i].value;
}
$( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
fruits= fruits+' '+fruit.toString();
}
else
{
fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;
}
}
<form>
<div>
<input type="checkbox" value="orange" id="orange" onclick="add(this);">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" value="apple" id="apple" onclick="add(this);">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" value="banana" id="banana" onclick="add(this);">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
Plain JavaScript solutions:
With one loop:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked"),
res = new Array(checkboxes.length);
function checkChecked() {
[].forEach.call(checkboxes, (checkbox, i) => {
checkbox.addEventListener("change", function() {
checkbox.checked ? res[i] = checkbox.value : res[i] = "";
checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
With two loops:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked");
function getResult() {
var res = "";
[].forEach.call(checkboxes, checkbox => {
checkbox.checked ? res += checkbox.value + "," : false
})
res = res.replace(/(,$)/, "");
return res;
}
function checkChecked() {
[].forEach.call(checkboxes, checkbox => {
checkbox.addEventListener("change", function() {
checked.innerHTML = getResult();
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>

Totalling the value of two radio buttons as a shopping cart

The issue is:
I have four radio buttons and a check box.
Two radio buttons are with one name and two with another.
The last radio buttons with same name appear only when the check box is checked.
What I want is add the value of first radio button and the value of radio button that appears after the checkbox is checked.
So how do I total the two values using javascript or any other technique. I need it asap as I am working on a project. I need that to be done as in a shopping cart. It means if the user selects another radio button then the value of earlier one should be subtracted and the value of new one added.
<script>
// get list of radio buttons with name 'size'
var sz = document.forms['de'].elements['type'];
// loop through list
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var m=this.form.elements.total.value = this.value;
};
}
var sa = document.forms['de'].elements['glass'];
// loop through list
for (var i=0, len=sa.length; i<len; i++) {
sa[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var n=this.form.elements.total1.value = this.value;
};
}
$(document).ready(function () {
$('.a').hide();
$('#checkb').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('.a').show();
} else {
$('.a').hide();
}
});
});
</script>
<form action="sum.php" method="post" name="de">
<fieldset>
<table align="center">
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<tr><td colspan="100sp"><label>Do You want a screen guard or a tempered glass?</label><input type="checkbox" name="screen" value="yes" id="checkb" />
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
</table>
<p><label>Repair: Rs. <input type="text" name="total" value="0" readonly="readonly" /></label></p>
<p><label>Glass: Rs. <input type="text" name="total1" value="0" readonly="readonly" /></label></p>
<p><label>Total: Rs. <input type="text" name="total2" value="0" readonly="readonly" /></label></p>
</fieldset>
</form>
You can do this with the Jquery event Change(). I have added ID names to the input text elements and this Jquery lines:
Check the comments for each line.
$(document).ready(function() {
//HIDE AND SHOW EXTRA OPTIONS
$('.a').hide();
$('#checkb').change(function() {
$('.a').toggle();
});
//CHECK WHEN ANY RADIO INPUT CHANGES
$('fieldset').on('change','input[type=radio]',function(){
//Get the Value and wich field text will change
var value = $(this).attr('value'),
target = $(this).attr('name');
$('#'+target).val(value);
//Show the total
var total = parseInt($('#type').val(),10) + parseInt($('#glass').val(),10);
$('#total').val(total);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<label>
<input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<br>
<label>
<input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<br>
<input type="checkbox" name="screen" value="yes" id="checkb" />
<label>Do You want a screen guard or a tempered glass?</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
<br>
<p>
<label>Repair: Rs.
<input type="text" id="type" name="total" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Glass: Rs.
<input type="text" id="glass" name="total1" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Total: Rs.
<input type="text" id="total" name="total2" value="0" readonly="readonly" />
</label>
</p>
</fieldset>
</form>
You can do it by using a facility given by jquery. Please check the below code
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<script type="text/javascript">
var total = 0;
$('.myradio').on('click',function(){
//Here you can get the checkbox value from data-value attribute
alert($(this).data('value');
//Total the Values
total = total + $(this).data('value');
});
</script>
In above code you can easily get the data from checkbox when it is clicked...

Get dynamic Class Names

For testing I have the alert, so the problem seem to be before the alert.
it throws errors at:
var firstPrevClass= "categClass"+PrevClass;
var newCategory = document.getElementsByClassName(firstPrevClass);
Uncaught TypeError: undefined is not a function
Basically in function addCategory I want to create dynamically new divs with different class names (which is creating dynamically).
After that I want to append the new category after the last category.
In function addField I want to put a new field at the category which selected from the selection box.
In function getClass I get the selected className so I can create a new field in the selected div.
How to do it?
/*add new category to SelextBox*/
function addCategory() {
var categoryValue = document.getElementById("newCateg").value;
var y = document.getElementById('selectCategory');
var option = document.createElement("option");
var hid = document.getElementById("nextValue").value;
var newClass = "categClass" + hid;
option.setAttribute("class", newClass);
option.value = categoryValue;
option.text = categoryValue;
y.add(option);
var PrevClass = hid-1 ;/*i do this to get the first previous class*/
var firstPrevClass= "categClass"+PrevClass;
alert(newClass);
var newCategory = document.getElementsByClassName(firstPrevClass);
var div = document.createElement('div');
div.setAttribute('class',newClass );
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var input_checkC = document.createElement('input');
input_checkC.setAttribute('type', 'checkbox');
input_checkC.setAttribute('class', 'check');
var textNodeCateg = document.createTextNode(categoryValue);
div.appendChild(a);
div.appendChild(input_checkC);
div.appendChild(textNodeCateg);
var last = newCategory.length;
newCategory[last].appendChild(div);
document.getElementById("nextValue").value++;
alert(newClass);
}
function getClass(sel) {
var x =sel.options[sel.selectedIndex].className;
document.getElementById("submitSelection").value=x;
}
function addField() {
var val = document.getElementById("submitSelection").value;
var existedCategory = document.getElementsByClassName(val);
var fieldValue = document.getElementById("newField").value;
var div = document.createElement('div');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
existedCategory.appendChild(div);
}
<ul>
<li>Προσθέστε το όνομα της νέας κατηγορίας</li>
<p>Ονομα Kατηγορίας:
<label>
<input type="text" id="newCateg" />
</label>
<input type="button" id="addCateg" value="Προσθήκη" onclick=" addCategory()" />
</p>
<p> </p>
<li>Επιλέξετε κατω απο ποια κατηγορία θα ανήκει το νεο πεδίο και εισάγεται το όνομα του νέου πεδίου.</li>
<p>Κατηγορία:</p>
<input type="hidden" value="4" id="nextValue" />
<input type="hidden" value="" id="submitSelection" />
<select id="selectCategory" onchange="getClass(this)">
<option>Επιλογή ...</option>
<option class="categClass1">Εξοδα Κατοικίας</option>
<option class="categClass2">Εξοδα Εκπαίδευσης</option>
<option class="categClass3">Εξοδα Ψηχαγωγίας</option>
</select>
<p>Ονομα πεδίου:
<label>
<input type="text" id="newField" />
<input type="button" value="Προσθήκη" onclick="addField()" />
<br />
</label>
</p>
<div class="class_1">
<p class="titles">
<input type="checkbox" class="catChk1 check" onchange="checkAll(subCheck1,subChks)" />Εξοδα Kατοικιας</p>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Ενοίκιο
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Θέρμανση
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Διάφορα Yλικά
<input type="text" />
</br>
</div>
<div class="class_2">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll(this)" />Εξοδα Εκπαίδευσης παιδιού</p>
<div class="field">
<input type="checkbox" class="check" />Φροντιστήρια
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />Βιβλία
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />Σχολική Υλη
<input type="text" />
</br>
</div>
<div class="class_3">
<p class="titles">
<input type="checkbox" class="check chk" onchange="checkAll(this)" />Για Ψυχαγωγία</p>
<div class="field">
<input type="checkbox" class="check" />
<label>Θέατρο</label>
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />
<label>Ψάρεμα</label>
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />
<label>Γήπεδο</label>
<input type="text" />
</br>
</div>

Categories