Alert displaying only parts of arguments - javascript

Here is a snippet/html of my work.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
'images/img-6.jpg',
'images/img-7.jpg'
];
var usedImages = {};
var usedImagesCount = 0;
var score = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
function check(){
x = prompt('What is the movie title?');
var y;
if (document.canvas.src=='images/img-1.jpg'){
y = 'The Expandables';}
if (document.canvas.src=='images/img-2.jpg'){
y = 'License to Wed';}
if (document.canvas.src=='images/img-3.jpg'){
y = "Schindler's List";}
if (document.canvas.src=='images/img-4.jpg'){
y = 'The Heartbreak Kid';}
if (document.canvas.src=='images/img-5.jpg'){
y = 'The Interview';}
if (document.canvas.src=='images/img-6.jpg'){
y = 'How To Train Your Dragon 2';}
if (document.canvas.src=='images/img-7.jpg'){
y = 'Avatar';}
if (y == x){
score = score + 10;
alert('Your points is ', score ,'.');}
else{
score = score;
alert('Your points is ', score ,'.')}
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
<html>
<body>
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Start!">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
<input onclick="check();" type=button value="Answer!">
</form>
</body>
</html>
When I run the JScript:
The output is OK except that the JScript alert is:
Your points is
regardless if my answer was right or wrong.
Why doesn't it display the score? What was my mistake?

You can concatenate strings using +, not using ,:
alert('Your score is ' + score + '.');

Related

Javascript for card shuffle failing

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"
}

Loop through the sum of the two inputs until in doubled (javascript)

I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>

On mouse hover, display the corresponding sizes of bars, as mentioned in the input field

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);
});
});
});

how to get different winning% in decreasing order for number of winners?

var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank &nbsp &nbsp Winning% &nbsp &nbsp &nbsp &nbsp &nbsp Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + "&nbsp<input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/>&nbsp<input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}

Open modal window after form calculations function is complete

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()

Categories