Open modal window after form calculations function is complete
I have a basic form that has check boxes. Each checkbox is a different (simple) calculation. At the end of the function some more calculations are done and stored in variables.
I need to first run this calculation function from an onclick event and then display them in a modal window.
I am using Magnific-Pop up at the moment.
I know that the calculations have to be done first so the variables have the data. But I don’t know how to run the function and then pop up the window.
Now, when the button is clicked the window opens before the function is run.
Form button
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
The Modal window
$('.ajax-popup-link').magnificPopup({
items: {
src: '#popup',
type: 'inline',
//preloader: true,
},
});
This code displays a div with all the variables. The constant variables display but not the final calcs.
Here is the div
<div id="popup" class="white-popup mfp-hide">
<table class="data savings">
<thead>
<tr>
<th colspan="2"><script>document.write(VarFromCalc);</script></th>
</tr>
</thead>
<tbody>
<tr>
<td>Number of patients with potential Reduced Length of Stay</td>
<td class="stay" id="stay">$ <script>document.write(totalN);
</script> </td>
</tr>
</tbody>
</table>
If the modal window (of course) opens before the calculations are done the values are 0.
I hope this makes sense. If you need more info let me know.
Here is the calculation script.
<script>
var n3, n4, n5, n6, totalW, totalB, totalU, totalT, totalN;
var finalCalc;
var n7;
function calculate() {
if (document.getElementById('check1').checked) {
var check01 = 6 * 7.08;
var c01 = check01.toFixed(2);
}
else {var c01 = 0;}
if (document.getElementById('check2').checked) {
var check02 = 4 * 4.62;
var c02 = check02.toFixed(2);
}
else {var c02 = 0;}
if (document.getElementById('check3').checked) {
var check03 = 6 * 13.20;
var c03 = check03.toFixed(2);
}
else {var c03 = 0;}
if (document.getElementById('check4').checked) {
var check04 = 6 * 16.00;
var c04 = check04.toFixed(2);
}
else {var c04 = 0;}
if (document.getElementById('check5').checked) {
var check05 = 3 * 1.32;
var c05 = check05.toFixed(2);
}
else {var c05 = 0;}
if (document.getElementById('check6').checked) {
var check06 = 1 * 12.30;
var c06 = check06.toFixed(2);
}
else {var c06 = 0;}
if (document.getElementById('check7').checked) {
var check07 = 4 * 3.16;
var c07 = check07.toFixed(2);
}
else {var c07 = 0;}
if (document.getElementById('check8').checked) {
var check08 = 4 * 4.68;
var c08 = check08.toFixed(2);
}
else {var c08 = 0;}
if (document.getElementById('check9').checked) {
var check09 = 3 * 12.91;
var c09 = check09.toFixed(2);
}
else {var c09 = 0;}
if (document.getElementById('check10').checked) {
var check10 = 3 * 13.55;
var c10 = check10.toFixed(2);
}
else {var c10 = 0;}
if (document.getElementById('check11').checked) {
var check11 = 3 * 50.60;
var c11 = check11.toFixed(2);
}
else {var c11 = 0;}
if (document.getElementById('check12').checked) {
var check12 = 4 * 11.36;
var c12 = check12.toFixed(2);
}
else {var c12 = 0;}
if (document.getElementById('check13').checked) {
var check13 = 1 * 93.58;
var c13 = check13.toFixed(2);
}
else {var c13 = 0;}
if (document.getElementById('check14').checked) {
var check14 = 3 * 18.48;
var c14 = check14.toFixed(2);
}
else {var c14 = 0;}
if (document.getElementById('check15').checked) {
var check15 = 3 * 39.93;
var c15 = check15.toFixed(2);
}
else {var c15 = 0;}
if (document.getElementById('check16').checked) {
var check16 = 2 * 5.98;
var c16 = check16.toFixed(2);
}
else {var c16 = 0;}
if (document.getElementById('check17').checked) {
var check17 = 1 * 12.30;
var c17 = check17.toFixed(2);
}
else {var c17 = 0;}
if (document.getElementById('check18').checked) {
var check18 = 1 * 50.73;
var c18 = check18.toFixed(2);
}
else {var c18 = 0;}
if (document.getElementById('check19').checked) {
var check19 = 3 * 4.36;
var c19 = check19.toFixed(2);
}
else {var c19 = 0;}
if (document.getElementById('check20').checked) {
var check20 = 3 * 284.58;
var c20 = check20.toFixed(2);
}
else {var c20 = 0;}
if (document.getElementById('check21').checked) {
var check21 = 1 * 214.27;
var c21 = check21.toFixed(2);
}
else {var c21 = 0;}
if (document.getElementById('check22').checked) {
var check22 = 2 * 78.00;
var c22 = check22.toFixed(2);
}
else {var c22 = 0;}
if (document.getElementById('check23').checked) {
var check23 = 4 * 6.13;
var c23 = check23.toFixed(2);
}
else {var c23 = 0;}
if (document.getElementById('check24').checked) {
var check24 = 1 * 4.78;
var c24 = check24.toFixed(2);
}
else {var c24 = 0;}
if (document.getElementById('check25').checked) {
var check25 = 2 * 14.52;
var c25 = check25.toFixed(2);
}
else {var c25 = 0;}
if (document.getElementById('check26').checked) {
var check26 = 1 * 229.44;
var c26 = check26.toFixed(2);
}
else {var c26 = 0;}
if (document.getElementById('check27').checked) {
var check27 = 1 * 9.68;
var c27 = check27.toFixed(2);
}
else {var c27 = 0;}
var h51 = (parseFloat(c01) + parseFloat(c02) + parseFloat(c03) + parseFloat(c04) + parseFloat(c05) + parseFloat(c06) + parseFloat(c07) + parseFloat(c08) + parseFloat(c09) + parseFloat(c10) + parseFloat(c11) + parseFloat(c12) + parseFloat(c13) + parseFloat(c14) + parseFloat(c15) + parseFloat(c16) + parseFloat(c17) + parseFloat(c18) + parseFloat(c19) + parseFloat(c20) + parseFloat(c21) + parseFloat(c22) + parseFloat(c23) + parseFloat(c24) + parseFloat(c25) + parseFloat(c26) + parseFloat(c27));
//per month calcs
var j3 = parseFloat(100);
var j4 = parseFloat(200);
var j5 = parseFloat(250);
var j6 = parseFloat(200);
var j7 = parseFloat(600);
var k3 = parseFloat(j3) * 12;
var k4 = parseFloat(j4) * 12;
var k5 = parseFloat(j5) * 12;
var k6 = parseFloat(j6) * 12;
//var k7 = parseFloat(j7)*12;
var l3 = parseFloat(3573);
var l4 = parseFloat(2033);
var l5 = parseFloat(4706);
var l6 = parseFloat(3437);
var m3 = parseFloat(j3)*parseInt(l3);
var m4 = parseFloat(j4)*parseInt(l4);
var m5 = parseFloat(j5)*parseInt(l5);
var m6 = parseFloat(j6)*parseInt(l6);
n3 = Math.round(parseFloat(k3)*parseFloat(l3));
n4 = Math.round(parseFloat(k4)*parseFloat(l4));
n5 = Math.round(parseFloat(k5)*parseFloat(l5));
n6 = Math.round(parseFloat(m6) * 12);
n7 = Math.round(parseFloat(j7) * parseFloat(h51) * 12);
//STORE FINAL CALCS
totalW = n3.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalB = n4.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalU = n5.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalT = n6.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalN = n7.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var totalCalc = Math.round(parseFloat(n3) + parseFloat(n4) + parseFloat(n5) + parseFloat(n6) + parseFloat(n7));
finalCalc = totalCalc.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$('.ajax-popup-link').click();
}
</script>
Then i try to show the vars in the hidden div popup as such
<tr>
<td>Total ID/AST Cultures</td>
<td class="cultures" id="cultures">$ <script>document.write(totalT);</script></td>
</tr>
Google Charts Code
var data = google.visualization.arrayToDataTable([
['Element', 'Savings', { role: 'style' }],
['Reduced Length of Stay', n7, ''],
['Total ID/AST Cultures', n6, ''],
['Urine', n5, ''],
['Blood', n4, ''],
['Wound/Abscess', n3, '' ],
]);
I don't know much about magnificPopup, but in this case, you can actually just add a hidden div with "ajax-popup-link" class, and remove this class from the link.
in the Calculate() function, after everything is done, you call "$('.ajax-popup-link').click()" to bring up the modal.
To implement it, do like following:
change
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
to
<input type="button" class="calculate" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
To correctly set the calculated value to the popup window, you can add a id to the node that need to display the value, like following html code:
<th colspan="2" id="var_from_calc"></th>
And in the calculate() function, after you have finished calculating, add this code:
$('#var_from_calc').html(VarFromCalc);
$('#stay').html(totalN);
$('.ajax-popup-link').click()
Related
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
function draw() {
var nums = document.getElementById("number").value.split(",");
console.log(nums);
var w = 40;
var factor = 20;
var n_max = Math.max.apply(parseInt, nums);
var h_max = factor * n_max;
console.log("h max is " + h_max);
console.log("n max is " + n_max);
//var h_max = Math.max(h);
//var a = parseInt(nums);
//var create = document.getElementById("shape");
for (var i = 0; i <= nums.length; i++) {
//var x = parseInt(nums[i]);
//var final_width = w / x;
var x_cor = (i + 1) * w;
//var y_cor = i * w * 0.5;
var h = factor * nums[i];
console.log(x_cor);
console.log(h);
//console.log(h_max);
var change = document.getElementById("histContainer");
//change.className = 'myClass';
var bar = document.createElement("div");
bar.className = 'myClass';
//var c_change = document.createElement("div2");
//change.appendChild(c_change);
change.appendChild(bar);
console.log(change);
//change.style.x.value = x_cor;
//change.style.y.value = y_cor;
bar.style.position = "absolute";
bar.style.top = (h_max - h) + "px";
//bar.style.transform = "rotate(-1deg)"
bar.style.left = i * w * 1 + "px";
bar.style.backgroundColor = "rgb(1,211,97)";
bar.style.opacity = "0.6";
bar.style.width = w + "px";
bar.style.height = h + "px";
//var color1 = document.getElementById("histContainer");
//var bar_color = document.createElement("div");
//color1.appendChild(change);
//bar.style.color = "rgba(1,211,97,0.6)";
}
}
function color() {
//draw();
var change1 = document.getElementsByClassName('myClass');
for (var i = 0; i < change1.length; i++) {
change1[i].style.backgroundColor = "rgb(255,0,27)";
console.log("Change1 = " + change1[i]);
}
// var bar1 = document.createElement("div2");
// change1.appendChild(bar1);
// console.log(change1);
//change1.style.backgroundColor = "rgb(1,,254,16)";
}
$(document).ready(function() {
$(document).on("mouseover", ".myClass", function() {
//var number = this.nums;
//$(this.nums).text($(this.nums).index());
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout", ".myClass", function() {
$(this).css("opacity", shade);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Number:<input type="text" id="number" /><br>
<input type="button" id="button1" value="Draw" onClick="draw()" /><br>
<input type="button" id="button2" value="Change Color" onClick="color()" /><br>
<div id="histContainer" style="position: relative;"> </div>
<!-- <label for="mouseover" id="label1">Bar Value</label><br>
<input type="text" name="mouseover" id="text2" value="0"/><br> -->
<!-- <input type="button" id="color_change" style="float: right;" value="Change Color" /> -->
My Question is- I have entered some numbers as Input, and corresponding histogram is made according to the input values. Now, I have created mouseover() on each bar, and WANT to display their proportionate sizes, as given in input.
Can you provide me some help? Only thing which i figured out was- I have to call my draw function in the jQuery mouseover.
REFER TO the draw() and jQuery function(last)
I have figured out the answer. It is required that the nums array has to be re-declared again.
Solution Achieved
$(document).ready(function() {
$(document).on("mouseover",".myClass", function(){
//var numbers = $("#number").serialize();
//var number = this.nums;
var nums = document.getElementById("number").value.split(",");
$(this).text(nums[$(this).index()]);
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout",".myClass", function() {
$(this).css("opacity", shade);
});
});
});
I have a weird problem with javascript mathematics here is my code :
<script>
function four() {
var price = document.getElementById("price").value;
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
</script>
and when the price is 100 ( price = 100 )
pish : 334.1666666666667
ghest : 167.08333333333331
how can i fix that ?
Here's a solution you had to parse the value that you get from your element.
function four() {
var priceUnparsed = document.getElementById("price").value;
var price= parseFloat(priceUnparsed );
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
alert(pishpardakht);
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
<input id="price" value="100">
<button onclick="four()">Go</button>
Im trying to calculate a price that is depending on how many rows you use in a textarea. This is what i have come up with so far. The only problem is its won't calculate, i think i have looked at it to much or something.
Let me explain a little, first of its for som textads.
There is a flatfee for minimum of 2 rows and then additional 10 for each new row, with a maximum of 10 rows.
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return false;
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
if (count.rows > 2) {
var additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
$('span.total').html(parseFloat(total.toString()).toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</p>
Modified your function a bit. Works now
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return {rows:split.length};
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
var additionalFees=0;
if (count.rows > 2) {
additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
//$('span.total').html(total.toString().toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</span></p>
https://jsfiddle.net/5mcbt8ua/4/
HTML
Flat Rate / First 2 rows: 70<BR>
Additional Rows: 10 per row
<div id="compute" contenteditable="true" style="border:1px solid #ccc;">
</div>
Total Price: <font id="total">0</font>
<BR>
<font id="msg"></font>
jQuery
var flatFee = 70;
var perRow = 10;
$('#compute').keypress(function(){
$("#msg").html('Press enter to compute');
var count = $(this).find('div').length;
var total = flatFee;
if(count > 1)
{
total = flatFee + (count * 10) - 10;
}
$("#total").html(total);
});
Currently when a button is clicked, it subtracts an inputted value. I want to have a preset value subtracted once a preset button is clicked. It would also be perferable that I could reuse a function later on a different button with different values like so:
var preset = function(val1, val2, val3, val4) {
//function to subtract from current values
}
$('presetButton').click(function(){
preset(1,2,3,4)
}
Here is the current function as I have it. The first button function works, but I wanted to copy it into a preset button with preset values. The function would not include $(this) because the button would not be in the same wrapper div and are not siblings.
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
$('#presets').click(function(){
//set up the subtracting and current variables
var subCal = 120;
var subPro = 24;
var subCarbs = 3;
var subFat = 1;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFat = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal)
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
//Add to presets to history
})
});
The HTML
<h1>Track your Macros</h1>
<div class="wrapper">
<div id="calories">
<div class="number"><p>1945</p></div>
<div class="label"><p>Calories</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="protein">
<div class="number"><p>200</p></div>
<div class="label"><p>Protein</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="carbs">
<div class="number"><p>173</p></div>
<div class="label"><p>Carbs</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="fats">
<div class="number"><p>50</p></div>
<div class="label"><p>Fats</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
</div>
<div id="presets"><img src="on-logo.png"></div>
Try
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
var preset = function(val1, val2, val3, val4) {
//set up the subtracting and current variables
var subCal = val1;
var subPro = val2;
var subCarbs = val3;
var subFat = val4;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFats = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal);
}
//apply new values
var applyHistory = function(id, val) {
$(id + ' .history').append("<p>" + val + "</p>");
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
applyHistory('#calories', subCal);
applyHistory('#protein', subPro);
applyHistory('#carbs', subCarbs);
applyHistory('#fats', subFat);
}
$('#presets').click(function(){
preset(120,24,3,1);
})
});
Demo: Fiddle