trying to do calculation of 2 input fields update in real-time - javascript

I am trying to calculate 2 input fields and display the result in real-time in div totalPrice
no matter what I've tried can't get it to work
thx
<script src="jquery-1.11.1.min.js">
jQuery('#field2').on('input propertychange paste', function() {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
}
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
});
</script>
<form action="" id="cakeform" onsubmit="return false;">
<input type="text" value="" size="20" name="field1" id="field1" class="rsform-input-box">
<input type="text" value="" size="20" name="field2" id="field2" class="rsform-input-box">
<div id="totalPrice"></div>
</form>

What about this http://jsfiddle.net/20Lgz8ey/2/
$('#field1,#field2').on('input propertychange paste', function() {
$('#totalPrice').html(parseFloat($("#field1").val()!=''?$("#field1").val():0)+parseFloat($("#field2").val()!=''?$("#field2").val():0));
});
also
<script src="jquery-1.11.1.min.js"></script>
<script>
code ....
</script>

$(document).ready(function () {
jQuery('#field2, #field1').on('input propertychange paste', function () {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
})
});
try this if it helps you.

Related

jS code is not working, not showing total

I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!
I was trying to use method Post on the form, removed it.
Also removed any styling.
function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £"
TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form action="#" id="Mangoform">
<div>
<div>
<div>
<span>Small: 1.3kg</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Large: 3.3kg</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Small: 5.0kg</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>Your Total:</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()">
</div>
</form>
if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed
as 38.97
(5.99*1)+(12.99*1)+(17.99*1)+2=38.97
if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93
Please point out the mistake. Thanks.
There is one extra closing curly bracket in getpkgPriceA function. You just need to remove it and also you need to add + sign while adding strings:
"Your Total: £" + TotalpkgPrice.toFixed(2);
Try this:
function getpkgPriceA(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA=theForm.elements["qtyA"];
if(QuantityA==null || QuantityA===false){
var totalpkgPriceA = 0;
return totalpkgPriceA;
}
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
function getpkgPriceB(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB=theForm.elements["qtyB"];
if(QuantityB==null || QuantityB===false){
var totalpkgPriceB = 0;
return totalpkgPriceB;
}
else{
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC=theForm.elements["qtyC"];
if(QuantityC==null || QuantityC===false){
var totalpkgPriceC = 0;
return totapkgPriceC;
}
else{
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal(){
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() +2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display='block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;
}
function hideTotal(){
var divobj = document.getElementById('totalprice');
divobj.style.display='none';
}
<form action="#" id="Mangoform">
<div >
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()" >
</div>
</form>
function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form id="Mangoform">
<div>
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="button" value="submit" onclick="calculateTotal();">
</div>
</form>
</body>
</html>
As it was pointed out previously with #Saurabh code. The other reason might be the missing + sign in divobj.innerHTML = "Your Total: £" TotalpkgPrice.toFixed(2) ; where it has to be corrected to divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;

how to insert id="getdobval" into input value?

I want to insert a value into <input type="text" id="getdobtval"> when I am selecting a range value.
For showing output in browser am using <span id="getdobtval"></span> instead of this span I want insert into text. How can I solve this using javascript?
jQuery(document).ready(function() {
$('#slider-bottom').slider().on('slide', function(ev) {
var finalvalue = '';
var finalbtvalue = '';
var finalbtprice = '';
var finalbitvalue = '';
finalbtprice = 250;
var newVal = $('#slider-bottom').data('slider').getValue();
var textval = parseInt(newVal);
if (textval >= 600 && textval < 6000) {
finalvalue = 0.075;
finalbitvalue = textval * finalvalue;
} else if (textval >= 6000 && textval < 30000) {
finalvalue = 0.070;
finalbitvalue = textval * finalvalue;
} else if (textval >= 30000) {
finalvalue = 0.065;
finalbitvalue = textval * finalvalue;
}
finalbtvalue = finalbitvalue / finalbtprice;
if (finalbtvalue) {
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
});
$('#slider-bottom').sliderTextInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="text" id="getdobtval" name="getdobtval">
<input type="submit" name="buynow">
</form>
Create a hidden input box with different id like dobtval
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="hidden" id="dobtval" name="dobtval"/>
<input type="submit" name="buynow">
</form>
And in JS use,
....
if (finalbtvalue) {
$('#dobtval').val(finalbtvalue.toFixed(8));// set value in input
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
....
id must be unique, but if you want same HTML then differentiate your elements by their tag name like,
$('span#getdobtval').html('....'); // use html() span/div
$('input#getdobtval').val('....'); // use val() for input/textarea

buttons don't work after append - jquery

buttons won't work after appended elements take up same Y position, why is this happening? I took the advice of other posts and made my onclick functions a certain way but I am still having issues
js:
var welldataArray = [];
var productiondataArray = [];
var radioSearchPartB = 0;
var productionjsonarray = [];
$(document).ready(function() {
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
$(document).on('click', '.searchButton', function(){
//validate
if(radioSearchPartB == 1){
var block1 = $("#block1").val().toUpperCase();
var firstcharBlock1 = block1.substring(0,1);
var secondcharBlock1 = block1.substring(1,3);
var secondParsed = parseInt(secondcharBlock1);
var block2 = $("#block2").val();
var block3 = $("#block3").val();
var block4 = $("#block4").val().toUpperCase();
var firstcharBlock4 = block4.substring(0,1);
var secondcharBlock4 = block4.substring(1,3);
var msg = "";
if(firstcharBlock1!= 'A' && firstcharBlock1!= 'B' && firstcharBlock1!= 'C' && firstcharBlock1!= 'D'){
msg+="First text box Invalid Format: First character Range A-D\n";
}
if(secondParsed < 1 || secondParsed > 16 || isNaN(secondParsed) || !($.isNumeric(secondcharBlock1))){
msg+="First text box Invalid Format: Second Character Range 1-16\n";
}
if(parseInt(block2) < 1 || parseInt(block2) > 126 || block2.length == 0 || isNaN(parseInt(block2)) ){
msg+="Second text box Invalid Format: Must be a number 1-126\n"
}
if(isNaN(parseInt(block3)) || parseInt(block3) < 1 || parseInt(block3) > 24 || block3.length == 0){
msg+="Third text box Invalid Format: Must be a number 1-24\n";
}
if(firstcharBlock4 != 'W' || parseInt(secondcharBlock4) < 4 || parseInt(secondcharBlock4) > 6){
msg+= "Fourth text box Invalid Format: W and then a number 4-6\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
$('#result1').empty();
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
var assemble = block1 + "-" + block2 + "-" + block3 + "-" + block4;
var check = false;
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim() == assemble){
for(var j = 0; j < productionjsonarray.length; j++){
if(productionjsonarray[j].location.trim() == welldataArray[i].trim()){
$('#result1').append(productionjsonarray[j].location.trim() + " "
+ productionjsonarray[j].date.trim() + " " + productionjsonarray[j].oilproduction.trim()
+ " " + productionjsonarray[j].waterproduction.trim() + " " + productionjsonarray[j].gasproduction.trim() + "<br>");
check = true;
}
}
}
}
if(check == false){
alert("No match to search");
return;
}
} else {
//validate
var block5 = $("#block5").val().toUpperCase();
var firstcharBlock5 = block5.substring(0,1);
var secondcharBlock5 = block5.substring(1,3);
var secondParsed5 = parseInt(secondcharBlock5);
var msg = "";
if(firstcharBlock5!= 'A' && firstcharBlock5!= 'B' && firstcharBlock5!= 'C' && firstcharBlock5!= 'D'){
msg+="text box Invalid Format: First character Range A-D\n";
}
if(secondParsed5 < 1 || secondParsed5 > 16 || isNaN(secondParsed5) || !($.isNumeric(secondcharBlock5))){
msg+="text box Invalid Format: Second Character Range 1-16\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
var check = false;
$('#result1').empty();
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim().indexOf(block5.trim()) >= 0){
$('#result1').append(welldataArray[i] + " " + welldataArray[i+1] + " " + welldataArray[i+2] + " " + welldataArray[i+3] + " " + welldataArray[i+4] + " " + welldataArray[i+5] + "<br>");
check = true;
}
}
if(check == false){
alert("No match to search");
return;
}
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
}
});
$.ajax({
type: "GET",
url: "welldata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('welldata').each(function(){ //code provided by stack overflow: http://stackoverflow.com/questions/6542187/xml-to-javascript-array-with-jquery
var location;
var welldepth;
var perfdepth;
var perfzone;
var stroke;
var strokepermin;
location = $('location', this).text();
welldepth = $('welldepth', this).text();
perfdepth = $('perfdepth', this).text();
perfzone = $('perfzone', this).text();
stroke = $('stroke', this).text();
strokepermin = $('strokepermin', this).text();
welldataArray.push(location);
welldataArray.push(welldepth);
welldataArray.push(perfdepth);
welldataArray.push(perfzone);
welldataArray.push(stroke);
welldataArray.push(strokepermin);
});
}
});
$.ajax({
type: "GET",
url: "productiondata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('productiondata').each(function(){
var location;
var date;
var oilproduction;
var waterproduction;
var gasproduction;
location = $('location', this).text();
date = $('date', this).text();
oilproduction = $('oilproduction', this).text();
waterproduction = $('waterproduction', this).text();
gasproduction = $('gasproduction', this).text();
productiondataArray.push(location);
productiondataArray.push(date);
productiondataArray.push(oilproduction);
productiondataArray.push(waterproduction);
productiondataArray.push(gasproduction);
});
$( "#searchButton" ).click(function() {
radioSearchPartB = $('input[name=searchChoice]:checked').val()
});
}
});
});
function loadPartB(){
document.getElementById("block1").maxLength = "3";
document.getElementById("block2").maxLength = "3";
document.getElementById("block3").maxLength = "2";
document.getElementById("block4").maxLength = "2";
document.getElementById("block5").maxLength = "3";
radioSearchPartB = $('input[name=searchChoice]:checked').val();
$('#result1').html('');
$('#result1').empty();
if(radioSearchPartB == 2){
$("#1stblocks").hide();
$("#1stex").hide();
$("#2ndblocks").show();
$("#2ndex").show();
} else {
$("#1stblocks").show();
$("#1stex").show();
$("#2ndblocks").hide();
$("#2ndex").hide();
}
}
html:
<!DOCTYPE html>
<html class="colorful">
<head>
<meta charset="utf-8">
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="css/final.css">
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="final.js"></script>
</head>
<body onload="loadPartB()">
Cameron Steinburg 734972
<br>
<h1>This is Part B</h1>
<br>
<h2>Oil Well Database</h2>
<div id="result1"></div>
<br>
<input type="radio" name="searchChoice" value="1" checked onchange="loadPartB()"> Search by specific location
<input type="radio" name="searchChoice" value="2" onchange="loadPartB()"> Search by section
<br>
<br>
<table id="1stblocks">
<tr>
<td><input type="text" id="block1">-</td>
<td><input type="text" id="block2">-</td>
<td><input type="text" id="block3">-</td>
<td><input type="text" id="block4"></td>
<td></td>
</tr>
</table>
<div id="1stex">
ex. B15-98-17-W5
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<table id="2ndblocks">
<tr>
<td><input type="text" id="block5"></td>
</tr>
</table>
<div id="2ndex">
ex. B15
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div>
<input type="submit" value="Search" class="searchButton">
<input type="submit" value="Clear" class="clearButton">
</div>
<br>
<br>
<h3>Main Page Part C Part D</h3>
</body>
</html>
Well, your buttons works if you remove onload="loadPartB()" from body and call the loadPartB(); in your document.ready()
$(document).ready(function() {
loadPartB();
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
you can use delegate() as :
$(document).delegate('click', '.clearButton', function (){
// your code
});
document : http://api.jquery.com/delegate/
this event alway set to new elements

when checkbox is checked it calculate the price but the issue it not appear in confirm

function fuelPrice()
{
var fuelPrice=0;
var theForm = document.forms["price"];
var withFuelPrice = document.getElementsByClassName("ful");
if(withFuelPrice.checked==true)
{
fuelPrice=30;
}
return fuelPrice;
}
function withPol()
{
var polishPrice=0;
var theForm = document.forms["price"];
var includeInscription = document.getElementsByClassName("pol");
if(includeInscription.checked==true){
polishPrice=50;
}
return polishPrice;
}
function driver()
{
var driverPrice=0;
var theForm = document.forms["price"];
var getDriv = document.getElementsByClassName("drv");
if(getDriv.checked==true){
driverPrice=50;
}
return driverPrice;
}
function calculateTotal()
{
var car1= 50
var total = fuelPrice() + withPol() + car1 + driver();
var text = "Total Price For the Renting "+total+ "BHD/Week";
//display the result
var divobj = document.getElementsByClassName('totalPrice');
divobj.style.display='block';
divobj.innerHTML = text;
return text;
}
function myFunction()
{
var name = calculateTotal()
confirm(name)
}
<form class="price"><p class="totalPrice booktxt">Total Price For the Renting 50BHD/Week<br> </p>
<input onclick="calculateTotal() " type="checkbox" class="ful">With Fuel<br>
<input onclick="calculateTotal() " type="checkbox" class="pol">Polishing 2 weeks<br>
<input onclick="calculateTotal() " type="checkbox" class="drv">Driver<br>
</form>
<button class="btn1" onclick="myFunction()">Add to cart</button>
I am having some issues to make the price appear in confirm so the user sees the price and confirm its ok or not when i click it show a blank popup. Also, can I know my mistake to avoid it in the future
You have to return something to show in that confirm box.
function fuelPrice() {
var fuelPrice = 0;
var theForm = document.forms["price"];
var withFuelPrice = theForm.elements["ful"];
if (withFuelPrice.checked == true) {
fuelPrice = 30;
}
return fuelPrice;
}
function withPol() {
var polishPrice = 0;
var theForm = document.forms["price"];
var includeInscription = theForm.elements["pol"];
if (includeInscription.checked == true) {
polishPrice = 50;
}
return polishPrice;
}
function driver() {
var driverPrice = 0;
var theForm = document.forms["price"];
var getDriv = theForm.elements["drv"];
if (getDriv.checked == true) {
driverPrice = 50;
}
return driverPrice;
}
function calculateTotal() {
var car1 = 50
var total = fuelPrice() + withPol() + car1 + driver();
var text = "Total Price For the Renting " + total + "BHD/Week"; // Store text in local variable
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = text;
return text; // Return text
}
function myFunction() {
var name = calculateTotal()
confirm(name) // Now it shows text from calculateTotal function
}
<form id="price">
<p id="totalPrice" class="booktxt">Total Price For the Renting 50BHD/Week<br> </p>
<input onclick="calculateTotal() " type="checkbox" id="ful">With Fuel<br>
<input onclick="calculateTotal() " type="checkbox" id="pol">Polishing 2 weeks<br>
<input onclick="calculateTotal() " type="checkbox" id="drv">Driver<br>
</form>
<button class="btn1" onclick="myFunction()">Add to cart</button>
Just add a return value to calculateTotal function. Like the following
return divobj.innerHTML;
Full function looks as follows:
function calculateTotal()
{
var car1= 50
var total = fuelPrice() + withPol() + car1 + driver();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Renting "+total+ "BHD/Week";
return divobj.innerHTML;
}

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

Categories

Resources