I have this working JS which checks if different checkboxes are or not checked and asigns a different price for each one that will later be summed up.
function priceCandy1() {
var priceCandy1 = 0;
var candy = document.getElementById("candy1");
if(candy.checked==true)
{
priceCandy1=13;
}
return priceCandy1;
}
function calculateTotal()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
document.getElementById('totalid').innerHTML = "$" + totalPrice;
}
Now I'm trying to code the equivalent in jQuery and this function does work:
$(function () {
var priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
return priceCandy1;
});
But I can't grab the returned price into a function that will add up every priceCandy#. Out of scope but I donĀ“t know how to fix it.
If it is an issue of scope like you say, you could declare priceCandy1 outside the function, as a global variable.
var priceCandy1;
$(function () {
priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
});
Then use priceCandy1 in your totalPrice function and it should be able to fetch it.
Wrap them in the same function:
$(function () {
var priceCandy1 = function() {
if($('#candy1').is(':checked')) {
return 13;
}
return 0;
},
calculateTotal = function()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
$('#totalid').text('$' + totalPrice);
};
calculateTotal();
});
Related
Can someone explain why my if statement doesn't work in the displayStorageSizeToConvert() function? Please and thank you!
var userInput = document.getElementById("userInput");
var kbButton = document.getElementById("k");
var mbButton = document.getElementById("mbButton");
var KilobyteDisplay = document.getElementById('KilobyteDisplay');
var megabyteDisplay = document.getElementById('megabyteDisplay');
var submitButton = document.getElementById('submit');
function displayStorageSizeToConvert() {
if (kbButton.clicked === true) {
return convertFrom.innerHTML = "KB";
}
else {
return convertFrom.innerHTML = "MB";
}
}
function convertStorageSizeFrom() {
if(convertFrom.value === "KB") {
KilobyteDisplay.innerHTML = userInput.value + " KB";
megabyteDisplay.innerHTML = userInput.value / 1000 + " MB";
}
}
It doesn't look like you're invoking your function anywhere.
Also, you should attach this function to a click handler:
function displayInKB() {
convertFrom.innerHTML = "KB";
}
function displayInMb() {
convertFrom.innerHTML = "MB";
}
kbButton.addEventListener('click', displayInKb);
mbButton.addEventListener('click', displayInMb)
You are not currently ever calling/triggering displayStorageSizeToConvert().
I think you are wanting to create a listener. You can add it like this:
kbButton.addEventListener('click', () => convertForm.innerHTML = "KB")
Lets see this script, that it's a simple carrousel
$script = {
init: function(){
this.heros(3000);
},
heros: function (time) {
var t;
var $hero = $('.hero');
var $images = $('.hero > div');
$hero.data('current', 0);
var $bullets = $('<div>').addClass('bullets');
for ( var i = 0; i<$images.length; i++ ) {
var $item = $('<span>');
$item.on('click', function () {
clearTimeout(t);
play( $(this).index() );
});
if(i==0) { $item.addClass('active') }
$bullets.append( $item );
}
var play = function (current) {
if(current==undefined) {
current = $hero.data('current');
}
var nextMargin;
if ( (current+1) == $images.length ) {
nextMargin = 0 ;
$hero.data('current',0);
} else {
nextMargin = (current + 1 )*100;
$hero.data('current', (current + 1));
}
$images.eq(0).css('marginLeft', -nextMargin + '%');
$bullets.find('span').eq($hero.data('current')).addClass('active').siblings().removeClass('active');
clearTimeout(t);
t = setTimeout(play, time);
}
$hero.append($bullets);
t = setTimeout(play, time);
},
}
The thing is that it works great, but only if there's just one .hero element.. if there are multiple the bullets mix up and it doesn't respect the .length
I know that option one should be rewrite it again, but Does anyone of you sees a quick fix that would make it reusable?
A single fiddle: https://jsfiddle.net/6z8n5pnq/
A multiple fiddle: https://jsfiddle.net/6z8n5pnq/1/
-EDIT-
I tried:
Defining a previous function, that is called on init
preheros: function(time) {
var self = this;
$('.heros').each(function(){
self.heros($(this), time);
});
},
And editing The begining of heros:
heros: function ($hero, time) {
var t;
/*var $hero = $('.hero');*/
var $images = $hero.find('>div');
but no success...
any idea?
-EDIT-
GOD, it's $('.hero').each not $('.heros').each it was working!
The easiest way to do this is to isolate context for each .hero component by using $(selector).each function. Slightly corrected your fiddle https://jsfiddle.net/6z8n5pnq/2/
function apply($hero, time){
var t;
var $images = $hero.children('div');
//all your logic here...
}
$script = {
init: function () {
this.heros(3000);
},
heros: function (time) {
$('.hero').each(function(){
apply($(this), time);
});
},
}
I'm trying to build a simple p.o.s entry in lightswitch html. And my problem is the total amount is not calculating in the correct event. I'm new to all this javascript and lightswitch so please forgive my innocence.
I have inserted a breakpoint in my "updateTotal function" the problem I have clearly is that it calls the updateTotal function once I click the addsales detail(When there is no data yet). What needs to happen is that it should call the updateTotal after I selected a product.
What am I doing wrong?
Below is the code I wrote. Can anybody help me?
myapp.AddEditSalesHeader.created = function (screen) {
// Write code here.
//Set the default values of the following fields.
screen.SalesHeader.InvoiceNo = "(Auto Invoice #)";
var vTime = new Date();
screen.SalesHeader.InvoiceTime = vTime;
screen.SalesHeader.ModePmt = "CASH";
screen.SalesHeader.Shipment = "PICK-UP";
screen.SalesHeader.PerDiscount = 0;
screen.SalesHeader.TotalDiscount = 0;
screen.SalesHeader.NetAmount = 0;
screen.SalesHeader.AmountReturn = 0;
screen.SalesHeader.CashReceived = 0;
screen.SalesHeader.ChangeDue = 0;
screen.findContentItem("InvoiceNo").isReadOnly = true;
screen.findContentItem("InvoiceDate").isReadOnly = true;
screen.findContentItem("TotalAmount").isReadOnly = true;
screen.findContentItem("NetAmount").isReadOnly = true;
};
myapp.AddEditSalesHeader.PerDiscount_postRender = function (element, contentItem) {
//Compute TotalAmount & NetAmount when PerDiscount value is entered
contentItem.dataBind("value",
function (PerDiscount) {
var vADisc = contentItem.screen.SalesHeader.TotalAmount * (PerDiscount / 100);
contentItem.screen.SalesHeader.TotalDiscount = vADisc;
contentItem.screen.SalesHeader.NetAmount = contentItem.screen.SalesHeader.TotalAmount - vADisc;
});
};
myapp.AddEditSalesHeader.TotalAmount_postRender = function (element, contentItem) {
function updateTotal() {
var InvDetail = contentItem.screen.SalesDetails.data;
var AmtDetail = 0;
InvDetail.forEach(function (sales) {
if (isNaN(sales.Amount)) {
AmtDetail = 0;
}
else {
//Update the TotalAmount
AmtDetail = AmtDetail + sales.Amount;
}
})
//Display the TotalAmount
contentItem.screen.SalesHeader.TotalAmount = AmtDetail;
contentItem.screen.SalesHeader.NetAmount = contentItem.screen.SalesHeader.TotalAmount
- contentItem.screen.SalesHeader.TotalDiscount;
}
//Set up a databind on screen.SaleDetails.count
contentItem.dataBind("screen.SalesDetails.count", function () {
updateTotal();}
);
}
myapp.AddEditSalesHeader.TotalDiscount_postRender = function (element, contentItem) {
// Write code here.
//Compute PerDiscount & NetAmount when the TotalDiscount value is entered
contentItem.dataBind("value",
function (TotalDiscount) {
if (TotalDiscount > 0) {
contentItem.screen.SalesHeader.PerDiscount = (TotalDiscount / contentItem.screen.SalesHeader.TotalAmount) * 100;
contentItem.screen.SalesHeader.NetAmount = contentItem.screen.SalesHeader.TotalAmount - TotalDiscount;
}
else {
contentItem.screen.SalesHeader.PerDiscount = 0;
}
});
};
myapp.AddEditSalesHeader.InvTime_postRender = function (element, contentItem) {
// Write code here.
this.setInterval(
function () {
var currentTime = new Date();
$(element).text(currentTime.toLocaleTimeString());
},
1000
);
};
//function CallGetTotAmt(operation) {
// $.ajax({
// type: 'post',
// data: {},
// url: '../Web/GetTotAmount.ashx',
// success: operation.code(function AjaxSuccess(AjaxResult) {
// operation.complete(AjaxResult);
// })
// });
//}
myapp.AddEditSalesHeader.Details_postRender = function (element, contentItem) {
// Write code here.
//Hide the save command button
$("[data-ls-tap='tap:{data.shell.saveCommand.command}']").hide();
//Hide the discard command button
$("[data-ls-tap='tap:{data.shell.discardCommand.command}']").hide();
};
myapp.AddEditSalesHeader.Cancel_execute = function (screen) {
// Write code here.
msls.showMessageBox("Close transaction? Closing will cause any unsaved changes to be discarded.", {
title: "System Advisory",
buttons: msls.MessageBoxButtons.yesNo
})
.then(function (result) {
if (result === msls.MessageBoxResult.yes) {
myapp.cancelChanges();
}
});
};
myapp.AddEditSalesHeader.Save_execute = function (screen) {
// Write code here.
//Get the total data in SalesHeader
myapp.activeDataWorkspace.ApplicationData.SalesHeaders.includeTotalCount().execute().then(function (result) {
var varInvNo = AutoInvNo(result);
//Set InvoiceNo before saving
screen.SalesHeader.InvoiceNo = varInvNo;
var InvDetail = screen.SalesDetails.data;
var varStock = 0;
InvDetail.forEach(function (entity) {
//Update ProductFile StockOnHand that have products in SalesDetail
varStock = entity.ProductFile.StockOnHand - entity.Quantity;
entity.ProductFile.StockOnHand = varStock;
entity.ProductFile.TranCode = "O";
entity.InvoiceNo = varInvNo;
})
myapp.commitChanges().then(null, function fail(e) {
msls.showMessageBox(e.message, { title: e.title }).then(function () {
screen.SalesHeader.InvoiceNo = "(Auto Invoice #)";
throw e;
});
});
});
};
//Utility
function AutoInvNo(InvNo) {
var InvNumber = 1;
var Entities = InvNo.results;
//Count the total data in SalesHeader
Entities.forEach(function (entity) {
InvNumber = InvNumber + 1;
});
//Return InvNumber value
return InvNumber;
};
myapp.AddEditSalesHeader.Print_execute = function (screen) {
// Write code here.
var LoadingDiv = $("<div></div>");
var Loading = $("<h1> Loading Report...</h1>");
Loading.appendTo(LoadingDiv);
LoadingDiv.appendTo($(element));
// Get Report
var HTMLContent = $("<div></div>").html(
"<object width='650px' height='650px' data='../Reports/BranchSalesReport.rdlc'/>"
);
// Make report appear on top of the Loading message
HTMLContent.css({
"margin-top": "-50px"
});
HTMLContent.appendTo($(element));
}
this will solve you problem: alls I have done is add the time interval to the code at the bottom so it knows to check the total multiple times... the post render function is only called once usually so the function inside wasn't actually being called.
function updateTotal() {
var InvDetail = contentItem.screen.SalesDetails.data;
var AmtDetail = 0;
InvDetail.forEach(function (sales) {
if (isNaN(sales.Amount)) {
AmtDetail = 0;
}
else {
//Update the TotalAmount
AmtDetail = AmtDetail + sales.Amount;
}
})
//Display the TotalAmount
contentItem.screen.SalesHeader.TotalAmount = AmtDetail;
contentItem.screen.SalesHeader.NetAmount = contentItem.screen.SalesHeader.TotalAmount
- contentItem.screen.SalesHeader.TotalDiscount;
}
this.setInterval(
function () {
//Set up a databind on screen.SaleDetails.count
contentItem.dataBind("screen.SalesDetails.count", updateTotal);
},1000);
and the below code solves the NaN within the Amt Discount and Net Amount:
myapp.AddEditSalesHeader.TotalDiscount_postRender = function (element, contentItem) {
// Write code here.
//Compute PerDiscount & NetAmount when the TotalDiscount value is entered
contentItem.dataBind("value",
function () {
if (contentItem.value > 0) {
contentItem.screen.SalesHeader.PerDiscount = (contentItem.value / contentItem.screen.SalesHeader.TotalAmount) * 100;
contentItem.screen.SalesHeader.NetAmount = contentItem.screen.SalesHeader.TotalAmount - contentItem.value;
}
else {
contentItem.value = 0;
}
});
};
I have this code
var wrapper = {
init: function (elemClass) {
this.className = elemClass || '.full-description';
this.wrapElems();
},
wrapElems: function () {
var $lines = $(this.className),
holder = [];
$lines.each(function (i, item) {
holder.push(item);
if (holder.length === 2) {
$(holder).wrapAll('<div class="w-row" />');
holder.length = 0;
}
});
$(holder).wrapAll('<div class="w-row" />');
}
};
wrapper.init();
I want to init the wrapper into a specific div, I try this
var init = wrapper.init();
$("#div-content").append(init);
It does not work.
Thanks for the help
you can append like this
$("#div-content").append("<script>wrapper.init();</script>");
I have a nested function that I want to call from outside.
var _Config = "";
var tourvar;
function runtour() {
if (_Config.length != 0) {
tourvar = $(function () {
var config = _Config,
autoplay = false,
showtime,
step = 0,
total_steps = config.length;
showControls();
$('#activatetour').live('click', startTour);
function startTour() {
}
function showTooltip() {
}
});
}
}
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});
I was hoping to call it by tourvar.showTooltip(); but I seem to be wrong :) How can I make showTooltip() available from outside the function?
since my previous answer was really a hot headed one, I decided to delete it and provide you with another one:
var _Config = "";
var tourvar;
// Module pattern
(function() {
// private variables
var _config, autoplay, showtime, step, total_steps;
var startTour = function() { };
var showTooltip = function() { };
// Tour object constructor
function Tour(config) {
_config = config;
autoplay = false;
step = 0;
total_steps = _config.length;
// Provide the user with the object methods
this.startTour = startTour;
this.showTooltip = showTooltip;
}
// now you create your tour
if (_Config.length != 0) {
tourvar = new Tour(_Config);
}
})();
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});
function outerFunction() {
window.mynestedfunction = function() {
}
}
mynestedfunction();