I have the following javascript:
<script type="text/javascript">
function changeBet(parseFloat(bet)) {
var moneyline = parseFloat(<?php echo json_encode($win) ?>);
var gain = parseFloat(bet * moneyline);
document.getElementById("PotentialGain").value = gain;
}
</script>
The php variable $win is successfully var_dump'ed as a float. When the variable gain = bet, PotentialGain displays the user input from BetAmount as expected. Here is my echo'ed php code:
echo '<tr>';
echo '<td>type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" ></td></tr><tr><td>Potential Gain:<input type="text" name="PotentialGain[]" id="PotentialGain" ></td></tr><tr><td><input type="Submit" name="send" value="Submit"></td>';
echo '</tr>';
However, I want gain(which is inputted as the PotentialGain value) to be the user input bet * the var moneyline.
The result is NaN. Is there a var that I am not parsing correctly to display the correct numerical value of gain?
Thanks for any help.
You can't put a function call where a parameter name is expected.
function changeBet(bet) {
bet = parseFloat(bet);
// rest of code
}
The problem is the incorrect syntax in this line:
function changeBet(parseFloat(bet)) {
you need to pass a parameter to the function, like this:
function changeBet(bet) {
Then, when you call the function, you can evaluate whatever argument you want to send through parseFloat:
changeBet(parseFloat(strBet));
Here is the final javascript that I used:
<html>
<script type="text/javascript">
function changeBet(bet) {
var moneyline = <?php echo $win ?>;
var gain = (bet * moneyline).toFixed(2);
document.getElementById("PotentialGain").value = gain;
}
</script>
</html>
My final notes are: 1. To remember to place the javascript function after the code with your php caclculations. 2. Thanks to everyone who clarified parseFloat is not necessary if you know the var is a int (or double in my case). 3. Thanks to everyone who clarified parseFloat did not belong in the function parameter.
Hopefully this helps others out!
Related
I can't seem to figure out how to do the object part, I need to make it calculate the age dynamically. I've written most of the stuff here and it works fine the only down side is my dynamic age calculation, I don't know what I'm doing wrong and can't find my mistake.
<html>
<head>
<title>WEB PROGRAMIRANJE</title>
</head>
<body>
<script type="text/javascript">
var niza=new Array (9,8,7,6,5,4,3,2,1);
var izbrisani=niza.shift();
var izbrisanip=niza.pop();
var sortirani=niza.sort();
// form an arrey delete first and last:
// sort the arrey:
document.write(sortirani);
function babati(a,b,c)
{
var total;
total=(a+b+c)/3;
alert(total);
}
document.write("<br>");
</script>
<input type="button" value="Call" onClick="babati(0,5,10)";>
<script type="text/javascript">
document.write("<br>");
var ucenik=new Object();
// giving them value to object elements:
ucenik.ime="Name";
ucenik.prezime="Surname";
ucenik.godina=2021;
ucenik.roden=2003;
// printing the object elements:
document.write(ucenik.ime);
document.write("<br>");
document.write(ucenik.prezime);
document.write("<br>");
document.write(ucenik.roden);
document.write("<br>");
// The function:
// This will calculate the age dinamicly This year - Birth year:
ucenik.vozrast=function()
{
this.godina - this.roden;
}
ucenik.vozrast();
document.write(ucenik.vozrast);
//This line above prints the dynamic age:
</script>
</body>
</html>
2 things.
Firstly, the function isn't returning any value so running it won't result in any output.
Secondly, in the document.write(ucenik.vozrast) it writes the function definition rather than running the function and writing the output.
Below is the fixed code.
ucenik.vozrast=function()
{
return this.godina - this.roden;
}
document.write(ucenik.vozrast());
first step you need to return your function expression. Something like this:
ucenik.vozrast= function() {
return this.godina - this.roden;
}
and when you want to paint that result in the DOM you can do something like this
let actualYears = ucenik.vozrast()
document.write(actualYears);
There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});
What is the best way to echo the variable get_parestotal?
Some help please!
Thank you
<script type="text/javascript">
$(document).ready(function(){
var get_parestotal = 0
$(".parestotal").each(function(){
get_parestotal += parseFloat($(this).text());
});
alert(get_parestotal);
});
</script>
<? echo json_encode($get_parestotal); ?>
You can log variables and so on in the console.
e.g.:
console.log(get_parestotal);
You can even concatenate witht he use of +
console.log('This is your variable'+get_parestotal)
You can even add styling to your log (color, background-color,...):
console.log('%cThis is your variable'+get_parestotal+'!','color:green;');
There are some alternatives to console.log() you could use:
console.warn();
console.info();
console.error();
console.debug();
You can either do alert(myvar) or console.log(myvar).
Caveat: console.log is only supported in certain browsers...see the link.
if you want a console output than use console.log(get_parestotal);
If I have a html document with this:
<p onclick="hiho('#name')"> clicky </p>
<script>
function hiho(namevar){
var1 = #Names.find.where().eq("name", namevar).findUnique();
if( var1 != null){
alert("HIHO");
}
}
</script>
How do I use the JavaScript variable?
Play won't compile properly because inside
var1 = #Names.find.where().eq("name", namevar).findUnique();
it cannot find the value of namevar.
One, pretty straightforward, solution could be:
<p onclick="hiho('#name')"> clicky </p>
<script>
var map = {
'#name': '#Names.find.where().eq("name", name).findUnique()'
};
function hiho(namevar){
var value = map[namevar];
if( value != null){
alert("HIHO: " + value);
}
}
</script>
Supposing that the name variables are strings.
You'll probably want to make an AJAX request back to the server. This page talks about that some toward the bottom, and about the routing code you'll need.
I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".