I m learning jquery a bit so i created this fiddle here http://jsfiddle.net/8FXFE/17/
this is my html code
<div class="textForm">
<input type="radio" name="txtNumber" value="100" checked="checked" />100
<input type="radio" name="txtNumber" value="200" />200
<input type="radio" name="txtNumber" value="500" />500
<input type="radio" name="txtNumber" value="1000" />1000
<input type="radio" name="txtNumber" value="10000" />10000
<input type="radio" name="txtNumber" value="other" />other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"
/>
</div>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ" checked="checked"
/>Space 1.
<br />
<input type="radio" name="txtSpace" value="SM" />Space 2.
<br />
</div>
<h3>Output:</h3>
this is css
#other_field {
display: none;
}
this is jquery
$(document).ready(function () {
console.log("parsed");
$("input[name='txtNumber'],input[name='txtSpace']").change(function () {
$("#output").text("Changed to "+$("input[name='txtNumber']:checked").val() + " " +$("input[name='txtSpace']:checked").val() + " +++++SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER++++++"
);
});
});
$(':radio').on('change', function () {
$('#other_field')[$(this).val() === 'other' ? 'show' : 'hide']();
});
$('#other_field').on('blur', function () {
var val = $(this).val();
if(isNaN(val)) {
alert('only numbers are allowed..');
}
else if(parseInt(val, 10) % 10 > 0) {
alert('only multiples of 10..');
}
});
How can i achieve actual output those shown in capital letters inside +++++++++++
SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER
Also How can i add dynamic value of hidden other_field (if selected)
var value = $("input[name='txtNumber']:checked").val();
if(value == "other"){
value = parseInt($("#other_field").val());
}
if(!value || isNaN(value)) value = 0;
var type = $("input[name='txtSpace']:checked").val();
var fixedMultiplier;
switch(type){
case "RJ": fixedMultiplier = 100; break;
case "SM": fixedMultiplier = 50; break;
default: fixedMultiplier = 1; break;
}
var computedValue = value * fixedMultiplier;
$("#output").text("Changed to "+ value + " " + type + " (" + computedValue + ")");
http://jsfiddle.net/8FXFE/19/
Maybe you should also add a handler to the textfield to update output on keyup.
Related
I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>
i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />
my goal is that when the user clicks the checkbox, it will count how many checked inputs there is with the same class name. I'm trying to send the var e into the counting function but I'm not sure about the right syntax. When I replace the e in here: var n = $( '.e:checked' ).length; with a className it is working. But I need it to be dynamic.
Edit for the question:
How can I get value from the console log to var in PHP?
View
<br>
<label>
<input onclick="b(this.className)"
class="tuesdayMorBar"
type="checkbox"
name="worker_name[]"
value="<?php echo $shift['fullname'];?>" />
Javascript
function b(e) {
var countChecked = function() {
var n = $('.e:checked').length;
alert(n + (n === 1 ? " is" : " are") + " checked!");
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
}
Remove onclick="b(this.className)". Define countChecked at global level. Set click event with $("input[type=checkbox]").on("click", countChecked);. Then you can use this.className inside countChecked. It will work fine.
View
<br>
<label>
<input class="tuesdayMorBar"
type="checkbox"
name="worker_name[]"
value="<?php echo $shift['fullname'];?>" />
Javascript
var countChecked = function() {
var n = $('.' + this.className + ':checked').length;
alert(n + (n === 1 ? " is" : " are") + " checked!");
};
$("input[type=checkbox]").on("click", countChecked);
You can query for selectors with specific classes and attributes using querySelectorAll.
Try with this:
function b() {
var checkedInputs = document.querySelectorAll("input.your-class-name[type='checkbox']:checked");
alert((checkedInputs.length === 1 ? "is" : "are") + " checked!");
}
I have made a working snippet for your problem #Victoria's Secret. Comments are mentioned in the snippet itself. See if this resolves your issue.
function b(e) {
let totalChecked = 0; // initialize the variable with 0;
$("input[type=checkbox]." + e).each(function() { // check every checkbox with class e(e has className)
//console.log($(this));
if ($(this).is(":checked")) { // check if checkboxed is checked
totalChecked++; // increment every time
}
});
alert(`class ${e}: ${totalChecked}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><label><input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka1" />kaka1
<input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka2" />kaka2
<input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka3" />kaka3
<br><br>
<input onchange="b(this.className)" class="lala" type="checkbox"
name="worker_name[]" value="lala1" />lala1
<input onchange="b(this.className)" class="lala" type="checkbox"
name="worker_name[]" value="lala2" />lala2
<br><br>
<input onchange="b(this.className)" class="jaja" type="checkbox"
name="worker_name[]" value="jaja1" />jaja1
<input onchange="b(this.className)" class="jaja" type="checkbox"
name="worker_name[]" value="jaja2" />jaja2
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
im kinda new to javascript. I would like to multiple the total value by the days value dynamically. Was trying for some time but couldnt find the solution. Thanks in advance.
$(document).ready(function() {
$('.kalorie').click(function() {
var varKalorie = $('input[name=kalorie]:checked').val()
$('.posilki').prop("disabled", false);
if (varKalorie == 1000) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val());
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total);
});
}
if (varKalorie == 1250) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.1;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 1500) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.2;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 2000) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.4;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
if (varKalorie == 2500) {
$('.posilki').click(function() {
var total = 0;
$('.posilki:checked').each(function() {
var posilkiChecked = $('.posilki:checked').length;
if (posilkiChecked >= 3) {
posilkiEach = parseFloat($(this).val()) * 1.6;
total += posilkiEach;
$('.qtyminus').prop("disabled", false);
$('.qtyplus').prop("disabled", false);
} else {
total = "Musisz zaznaczyc przynajmniej 3 dania";
}
});
$('#total').html(total + 'pln');
});
}
});
console.log($('#total').text());
// This button will increment the value
$('.qtyplus').click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name=' + fieldName + ']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name=' + fieldName + ']').val(0);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2 class="global-title">Cennik</h2>
<input type="radio" name="kalorie" class="kalorie" value="1000" />1000
<input type="radio" name="kalorie" class="kalorie" value="1250" />1250
<input type="radio" name="kalorie" class="kalorie" value="1500" />1500
<input type="radio" name="kalorie" class="kalorie" value="2000" />2000
<input type="radio" name="kalorie" class="kalorie" value="2500" />2500
<br/>
<br/>
<input type="checkbox" class="posilki" value="15" disabled/>Śniadanie
<input type="checkbox" class="posilki" value="10" disabled/>2 Śniadanie
<input type="checkbox" class="posilki" value="20" disabled/>obiad
<input type="checkbox" class="posilki" value="10" disabled/>podwieczorek
<input type="checkbox" class="posilki" value="15" disabled/>kolacja
<br/>Days
<input type='button' value='-' class='qtyminus' field='quantity' disabled/>
<input type='text' name='quantity' value='30' class='qty' id="days-input" disabled/>
<input type='button' value='+' class='qtyplus' field='quantity' disabled/>
<br/>
<br/>Total:
<div id="total">0 zł</div>
</div>
Since you mention are kind of new to javascript ... my main message is to put things in functions.
This obliges you to think: "okay, what exactly do I need to know to perform this?" ... well those are the parameters of your function.
Ad of course, functions dramatically reduces code, you don't have to copy/paste everything 6 times.
Notice: you could put all the functions within document.ready, if you want.
And, oh yes, I added label elements. This makes it nicer to the client.
Is this it?
<div class="container">
<h2 class="global-title">Cennik</h2>
<input type="radio" name="kalorie" class="kalorie" value="1000" id="r0" /><label for="r0">1000</label>
<input type="radio" name="kalorie" class="kalorie" value="1250" id="r1" /><label for="r1">1250</label>
<input type="radio" name="kalorie" class="kalorie" value="1500" id="r2" /><label for="r2">1500</label>
<input type="radio" name="kalorie" class="kalorie" value="2000" id="r3" /><label for="r3">2000</label>
<input type="radio" name="kalorie" class="kalorie" value="2500" id="r4" /><label for="r4">2500</label>
<br/><br/>
<input type="checkbox" class="posilki" id="sniadanie" value="15" ><label for="sniadanie">Sniadanie</label>
<input type="checkbox" class="posilki" id="sniadanie2" value="10" ><label for="sniadanie2">2 Sniadanie</label>
<input type="checkbox" class="posilki" id="obiad" value="20" ><label for="obiad">obiad</label>
<input type="checkbox" class="posilki" id="podwieczorek" value="10" ><label for="podwieczorek">podwieczorek</label>
<input type="checkbox" class="posilki" id="kolacja" value="15" ><label for="kolacja">kolacja</label>
<br/><br/>Days
<input type="button" value="-" class="qtyminus" field="quantity" >
<input type="text" name="quantity" value="30" class="qty" id="days-input" >
<input type="button" value="+" class="qtyplus" field="quantity" >
<br/>
<br/>Total:
<div id="total">0 zl</div>
</div>
<style>
label {
cursor: pointer;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// calculates the total price, displays it in id="total"
function calculateTotal(sum_price, days) {
var result = sum_price * days;
$('#total').html(result + ' zl');
return result; // not really being used
}
// reads the checked checkboxes, returns their sum value
function readSumPrice() {
var sum = 0;
$('.posilki').each(function(i) {
if(this.checked) {
sum += Number($(this).val());
}
});
return sum;
}
// what ever the client changes, triggers this function. We don't really care what has just been clicked on, we have to recalculate it anyway.
function somethingChanged() {
// first we want to check if three meals have been chosen
var numberOfMealsChosen = $( ".posilki:checked" ).length;
if(numberOfMealsChosen >= 3) {
// now we calculate
var sum_price = readSumPrice();
var days = Number($('#days-input').val());
calculateTotal(sum_price, days);
}
else {
$('#total').html('please choose 3 items');
}
}
// now the events
$(document).ready(function() {
// click on +
$('.qtyplus').click(function() {
var days = Number($('#days-input').val());
$('#days-input').val(days + 1);
somethingChanged();
});
// click on -
$('.qtyminus').click(function() {
var days = Number($('#days-input').val());
// let's put 0 as minimum
if(days > 0) {
$('#days-input').val(days - 1);
somethingChanged();
}
});
// click on checkbox
$('.posilki').click(function() {
somethingChanged();
});
// click on radio. triggers the calculation but doesn't really affect anything (yet?)
$('.kalorie').click(function() {
somethingChanged();
});
});
</script>
I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}