I need help. I need the javascript code for the following function:
n = 1 + (log(5156559813)/log(x))/log(3)
where n is the output and x is the input box.
How do I make the input box be the x? Do I use document.getElementById("x").innerHTML = 1 + (Math.log(5156559813) / Math.log(x)) / Math.log(3)?
I've searched but the wrong thing keeps coming up every time.
Here's my code:
<form class="uk-form">
<fieldset data-uk-margin>
<input type="text" placeholder="People in your group" id="x">
<button class="uk-button uk-button-primary">Go!</button>
<p id="number"></p>
</fieldset>
<script type="text/javascript">
function n(x){
return document.getElementById("number").innerHTML = 1 + (9.7123600597) / Math.log(x)) / 0.4771212547;
document.getElementById('x').addEventListener('change', function () {
document.getElementById('n').innerHTML = n(this.value);
}, false);
}
</script>
</form>
Whenever I hit my button, the page refreshes and I am back at the beginning again.
Thank you very much!
Use Math.log() for base e, Math.log10() for base 10 and Math.log2() for base 2. Note that log10 and log2 are currently not supported on Internet Explorer
Using Math.log():
function n(x)
{
return 1 + (Math.log(5156559813) / Math.log(x)) / Math.log(3);
}
x is your input, and n(x) is your output.
If you want this function to be calculated each time that an input's value is changed, you can attach an event listener:
// As you stated in the commentes, x can be found in <input id="x">.
document.getElementById('x').addEventListener('change', function () {
// If your output goes into an <input>
document.getElementById('n').value = n(this.value);
// If your output goes into an <div>, <span> or another non self-closing HTML tag:
document.getElementById('n').innerHTML = n(this.value);
}, false);
Related
I have a js array and I wanted to log a random song into a HTML form when the button (named song) is pressed. I can log it into the console but I can't figure out how to use document.getElementById (I'm new to JS so please bear with me). I appreciate any help.
JavaScript:
var i = Math.floor(Math.random() * 10) + 1;
function randSong() {
var listOfSongs = ['Killomanjaro','No Sad No Bad','Doomsday','Solitaire',
'Distance','Roll In Peace','Bank Account','SAD!','Moonlight','Swimming Pools'];
console.log('Alexa, play',listOfSongs[i]);
}
randSong();
HTML:
<form>
Random Song:<input type="text" id="RandSong" name="song"/>
<input type="button" value="Song" onclick="randSong()"/>
</form>
var i = Math.floor(Math.random() * 10);
function randSong() {
var listOfSongs = ['Killomanjaro','No Sad No Bad','Doomsday','Solitaire',
'Distance','Roll In Peace','Bank Account','SAD!','Moonlight','Swimming Pools'];
console.log('Alexa, play',listOfSongs[i]);
document.getElementById('RandSong').value = listOfSongs[i];
}
randSong();
This should do it. Also, get rid of the +1 when you set the value for i. Math.random will return between 0 and 1. Arrays start at 0, so the way you wrote it could result in getting a 10, which would be out of the range.
I am trying to create a simple "guess the number game" in a web page where a user is the one thinking of the number and the computer is to guess the number that the user is thinking (no user input required). I need to create three buttons for user to respond to the computer's guess: Guess Higher, Guess Lower, Correct. I am not sure how to make the GuessHigher() and GuessLower() function work. Here is the java script code:
function getFieldValue(target) {
var elm = document.getElementById(target);
var val = parseInt(elm.value);
return val;
}
function getCompGuess() {
var upper = getFieldValue("UPPER");
var lower = getFieldValue("LOWER");
return (parseInt((upper + lower) / 2))
}
/* User starts game. */
function play() {
var remaining = getFieldValue("REMAINING");
var compGuess = getCompGuess()
var compElm = document.getElementById("COMP_GUESS")
compElm.innerHTML = compGuess
}
function GuessHigher() {
}
function GuessLower() {
}
function correct() {
alert ("YAY! Thank you for playing");
}
Here is the HTML code:
<html>
<head>
<meta charset="UTF-8">
<script src="lab1a.js"></script>
</head>
<body>
Guess a number game: <br/> <br/>
Upper Bound: <input id="UPPER" type="text"></input> <br/>
Lower Bound: <input id="LOWER" type="text"></input> <br/>
Guesses Remaining: <input id="REMAINING" type="text"></input> <br/>
<button onclick="play()">Play!</button> <br/>
Computer's Guess: <span id="COMP_GUESS"></span> <br/>
<button onclick="GuessHigher()">Guess Higher</button>
<button onclick="GuessHigher()">Guess Lower</button>
<button onclick="correct()">Correct!!!</button>
</body>
</html>
GUESS HIGHER:
It might not be elegant, but you could try to take the number last guessed and ADD to it any number within difference of UPPER BOUND-LAST GUESS. For example, lets say we have a number line with UPPER=10 and LOWER=0
0|----------|10
and we guess 5 as the computer. Now, if we want to guess higher we're going to need a place holder for our OLD Guess (5), and were going to need to decrease the guessing range so we don't go over our Upper boundry.
0|----<5>----|10, Imagine zooming in on only the top half 5>---10:
5>----|10.
This new range I called availableGuessingRange which is equal to 10-5 or 5.
We're only going to let the computer pick a new number between 1 and 5 now using Math.random.
Let's say it picks 3. Now we can bring that number back to our old guess by adding it (ie. 5+3=8), now 8 is the computers NEW GUESS.
I think it could be something like this:
var lastGuess=document.getElementById("COMP_GUESS").value
var avaliableGuessingRange = upper-lastGuess;
return Math.floor(Math.random()*avaliableGuessingRange)+lastGuess
for GUESS LOWER: I think it would be a similar set up except it uses lastGuess-lower to create the new range and you'll be subtracting the new guess from the last guess to move DOWN the number line.
The way I've written the code currently won't work because of variable scopes, but I think the logic should work.
I made fiddle out of this, and refactor the code tini little bit, inline listeners are considered bad practice. You should consider using some linter as there was some syntax error, mainly you were not terminating your statements; <--- See, this was typo actually, I terminated the sentence accidently with ; instead of .
(function() {
//getting references to buttons
var high = document.getElementById('high');
var lower = document.getElementById('lower');
var btn_correct = document.getElementById('correct');
//setting listeners
high.addEventListener('click', GuessHigher);
lower.addEventListener('click', GuessLower);
btn_correct.addEventListener("click", correct);
function getFieldValue(target) {
var elm = document.getElementById(target);
return parseInt(elm.value);
}
function getCompGuess() {
var upper = getFieldValue("UPPER");
var lower = getFieldValue("LOWER");
return (parseInt((upper + lower) / 2));
}
/* User starts game. */
function play() {
var remaining = getFieldValue("REMAINING");
var compGuess = getCompGuess();
var compElm = document.getElementById("COMP_GUESS");
compElm.innerHTML = compGuess;
}
function GuessHigher() {
console.log('higher');
}
function GuessLower() {
console.log('lower');
}
function correct() {
console.log("YAY! Thank you for playing");
}
}());
<body>
Guess a number game:
<br/>
<br/>Upper Bound:
<input id="UPPER" type="text">
<br/>Lower Bound:
<input id="LOWER" type="text">
<br/>Guesses Remaining:
<input id="REMAINING" type="text">
<br/>
<button id='play'>Play!</button>
<br/>Computer's Guess: <span id="COMP_GUESS"></span>
<br/>
<button id='high'>Guess Higher</button>
<button id='lower'>Guess Lower</button>
<button id='correct'>Correct!!!</button>
</body>
Try using code below
Math.floor(Math.random()*1000) // return a number between 0 and 1000
to generate random numbers
And use if else statements for
High, low , correct
JSFIDDLE
HTML:
<input type="number" id="strScore" class="attribScore" min=8 max=15>
<input type="number" id="strMod" class="attribMod" readonly="readonly">
Javascript:
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var strScore = $('#strScore').val();
var strMod = $('#strMod').val();
var update = function(score, mod) {
attribMod = (Math.floor(score / 2) - 5);
mod.value = attribMod;
};
update(strScore,strMod);
When the left input is updated with an ability score, the right input should reflect the ability modifier.
The commented section of javascript is perfectly functional, but I would really rather not have a separate function for every input that needs to be updated like this - one function is far easier to isolate and troubleshoot in the future. What I'd like to do is have one function to which I can pass the score and modifier input values as arguments (strScore and strMod in this case) and have it update the modifier field via the .oninput event. My attempt at this is below the commented section of javascript. I feel like I'm just not connecting the dots on how to call the function appropriately or correctly update the Modifier input passed to the function.
Phew. Got pulled away from the desk. Here is a solution for you. You just need to make sure that the strscore is set with an id number. This way you can relate to what strmod you want to change.
Ex. strScore1 = strMod1 and strScore2 = strMod2
This will setup a scenario where you don't have to touch anymore JavaScript to do this same function in the future. Allowing you to add as many score and mod couplets as you want in the HTML part.
We are binding the 'input' event on the class of .attributeScore which allows us to set the function. There is no need to pass in values because they are already included by default. As long as the score input has a class of .attributeScore, then it will fire that function.
We can use this.value to grab the score value, and then sub-string out the identity of the score aka 1 for strScore1 from the this.id attribute of the input field.
If we concatenate that sub-string with #strMod we can update the value of the corresponding strMod attribute with inline math.
Here is the jsfiddle: http://jsfiddle.net/hrofz8rg/
<!DOCTYPE html>
<html>
<head>
<title>Some JavaScript Example</title>
</head>
<body>
<input type="number" id="strScore1" class="attribScore" min=8 max=15>
<input type="number" id="strMod1" class="attribMod" readonly="readonly">
<br>
<br>
<input type="number" id="strScore2" class="attribScore" min=8 max=15>
<input type="number" id="strMod2" class="attribMod" readonly="readonly">
<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(".attribScore").bind({
'input':function(){
var attrib_num = this.id.substring(8,this.length);
$('#strMod' + attrib_num).val((Math.floor(this.value / 2) - 5));
}
});
</script>
</body>
</html>
Hope that helps! Enjoy!
Modifying your function to accept to dom nodes rather than two values would allow you to reuse the function in separate events that use different dom nodes relatively easily.
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var update = function($score, $mod) {
var attribMod = (Math.floor($score.val() / 2) - 5);
$mod.val(attribMod);
};
document.getElementById("strScore").oninput = function update(e) {
var $score = $('#strScore');
var $mod = $('#strMod');
update($score, $mod);
};
Even better though would be able to dynamically figure out which mod element you should target based on which score element the event was triggered on, then you wouldn't need a separate function to do the calculation/update while keeping the code dry.
I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">
i have a small javascript form
<div id="calculator-text"><h2>Tape calculator - based on cable size 1 mm to 28 mm, with 15% overlap</h2></div>
<form name="form1" method="post" action="">
<div id="calcformlabel"><label for="val2">Enter your cable size</label> (in mm)</div>
<div id="calcformtext1"><input type="text" name="val2" id="val2"></div>
<div id="calcformbutton"><input type="button" name="calculate" id="calculate" value="Calculate"></div>
<div id="calcformresult">The tape size you require is:- <span id="result1" class="maintext1"></span> (mm)</div>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
// get the input values
var val2 = parseInt(document.getElementById('val2').value);
// get the elements to hold the results
var result1 = document.getElementById('result1');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message
// to the array if it's not a number
if (isNaN(val2)) {
msg.push('<span class="maintext1">Enter your cable size</span>');
}
// if the array contains any values, display the error message(s)
// as a comma-separated string in the first <span> element
if (msg.length > 0) {
result1.innerHTML = msg.join(', ');
} else {
// otherwise display the results in the <span> elements
result1.innerHTML = val2 * 3.142 * 1.15;
}
};
</script>
basically this is a simple calculation
a) how can i get this to output to 2 decimal places (and obviously round up or down depending on -.5 = round down and +.5 = round up)
b) replace the input type button for an image ( i have tried the obvious code and >input type = image>, basically these do actually work but instead of displaying the actual result, they display the result in a split second then reload the page with the blank form again...
any help on this would be much appreaciated
thanks in advance
for a part of your question
you can round javascript to specific precision by
Link :Number rounding in JavaScript
var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111
The .toFixed() method lets you round off to n decimal places, so:
result1.innerHTML = (val2 * 3.142 * 1.15).toFixed(2);
I think the problem you're having with the image is that <input type="image"> defines the image as a submit button. Perhaps just include a standard image with an <img> tag rather than <input type="image">. If you give it an id='calculate' it should still work with your existing JS.
Or you could use a button element containing an img element so that you can specify the type (as not being submit):
<button type="button" id="calculate"><img src="yourimage"></button>
(I'm not sure that you need a form at all for this functionality since you don't seem to want to submit anything back to the server.)
To swap the button for an image, replace the button <input> with this code:
<img src="http://www.raiseakitten.com/wp-content/uploads/2012/03/kitten.jpg" name="calculate" id="calculate" value="Calculate" onclick="document.forms['form1'].submit();" />
It adds the image and a submit function for your form.
To round to two decimal places, use this function:
function twoDP(x){
return Math.round(x*100)/100
}
use it like this:
twoDP(100/3) //returns 33.33
it might also be relevant for you to use Math.PI
var result = val2 * Math.PI * 1.15 ;