How to get variables to pass to javascript math.random - javascript

So I am just totally clueless how to make this happen. Hoping someone could provide some guidance. I have built a chat system that allows random rolls of dice (for a D&D game). Within the chat div I have a form that allows to select the quantity of dice, as well as the dice type (ie. 4 sides, 6 sided, 10 sided, etc.). It then passes the form input with php into a chat.txt file. I am using ajax to display the chat.txt in the chat div.
So when I originally started I made it function for 1d20 (1 20 sided dice). And used x.value=Math.floor((Math.random()*20)+1) to make it pick a random number between 1 and 20. Well now I need it to be able to detect the quantity of dice, as well as the amount of sides of the dice(d4, d6, d8). Is there a way to pass the quantity and dice variables into the math.random ? and even better yet, then display each number separately (meaning say you roll 2 d6 and get a 5 and a 3. I would like to have it display the 5 and 3 separately. But that is not totally needed, mostly i need to know how to get different random ranges based on the $quantity and $dice. Or maybe a totally different approach that would work? Any and all help is much appreciated.
<div id="pageWrap">
<div id="expander"> Expand</div>
<?php
if(isset($_POST['submit']))//on submit
{
$roll = $_POST['roll'];
$quantity= $_POST['quantity'];
$dice = $_POST['dice'];
$nickname = htmlentities(strip_tags($_POST['nickname']));
$file = fopen('chat.txt', 'a');
fwrite($file, "<span>". $nickname . " :</span>" . $roll = str_replace("\n", " ", " <em> Rolls </em>$quantity $dice <em>for</em> $roll") . "\n");
fclose($file);
}
?>
<form action="" id="rollBox" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<input type="number" name="quantity" min="1" max="10">
<select name="dice">
<option value="d4">d4</option>
<option value="d6">d6</option>
<option value="d8">d8</option>
<option value="d10">d10</option>
<option value="d12">d12</option>
<option value="d20">d20</option>
</select>
<button type="submit" name="submit" >Roll</button>
</form>
<script>
$(document).ready(function () {
$('#rollBox').submit(function(e) {
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
e.preventDefault();
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {}
});
return false;
});
});
</script>
</form>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '200' ></textarea>
</form>
</div>

This function takes number of dices and dice type and will return an array filled with random number. However, what you need is loop, javascirpt loop to loop thru the number of dices and get a random value for each dice.
function getRandome (num_dice , dice_type) {
var result=[];
for (var i = 0 ; i < num_dice; i++) {
result[i] = Math.floor((Math.random()*dice_type)+1)
}
return result;
}
It's up to you how you want to get the input values, but here's a FULL ANSWER JS FIDDLE
now let's see this example
var num_dice = 5;// number of dices
var dice_type = 3;//3 faces
var randomArray = [] ;//will store the random result here as an array
randomArray = getRandome (num_dice , type );
var randomString = randomeArray.join(",");//convert the array to string adding a comma "," between indexes;
//assign the string result of random to a text field, div, span etc
$("#demo").val(randomString);//jquery
//OR
document.getElementById("demo").value = randomString;//javascript

Related

Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How do i make a sort of calculator using html and javascript?

I am a beginner programmer and I want to make this work but it doesn't. Could you Please help me and explain what's wrong? For example, if I enter under 20, I want it to tell me how long it will take me to walk to whatever planet I selected. Most of it is figuring out how to have the code store whatever option the user selects and then apply it to the age and use the data to calculate it. Thank you!
<legend>basic info</legend>
<p> What is your destination?
<select onchange = "selectDestination(this.value)">
<option value="mercury">Mercury</option>
<option value="venus">Venus</option>
<option value="mars">Mars</option>
<option value="jupiter">Jupiter</option>
<option value="saturn">Saturn</option>
<option value="uranus">Uranus</option>
<option value="neptune">Neptune</option>
<option value="pluto">Pluto</option>
</select>
<script type="text/javascript">
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
function selectDestination(selectedValue) {
window.alert(selectedValue + " distance=" + planets[selectedValue]);
}
</script>
</p>
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input type="number" id="userInput">
<input type="submit" onclick="age()">
</form>
<script type="text/javascript">
function age()
{
var input = document.getElementById("userInput");
alert(input);
}
if(age<20);
{
alert("YOU ARE UNDER 20");
var runSpeed=6.3;
var walkSpeed=2.1
var water = 1.5;
var calories = 2500;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24
document.write("it will take "+runTime+" hours and "+runDays+" days to make it to"+selectedValue);
}
if(21<age>45) {
alert("YOU ARE AT YOUR PHYSICAL PEAK");
var runSpeed=8.3;
var walkSpeed=3.1;
var water = 2;
var calories = 3000;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
if(age<45){
alert("YOU ARE PROBABLY TOO OLD TO TAKE THIS TRIP");
var runSpeed=5.3;
var walkSpeed=1.1;
var water=1.5;
var calories=3000;
var runTime = planets[selectedValue]/runSpeed;
var rundays = planets[selectedValue]/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
</script>
</p>
This code here doesn't work.
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
What you're declaring is an Array, and what you want to push into them is objects.
What you ideally want planets to look like is var planets = [ {planet: 'mercury', distance: 48000000}, {planet: 'venus', distance: 25000000 }, ... ]
Right now, nothing is happening because your syntax is looking for an object with a key of mercury or venus and not finding anything.
The next thing you should do is be able to console.log() whatever the user inputs as an age. Make sure your function age() accepts a parameter, so it might look more like age(val)
Once you're console.log() logs the age input by the user, you should be pretty close. All you have to do after that is grab the planet the user selected, and you can do that by looping through your planets array and matching what the user selected with what is in the array. Something like planets.filter(planet => planet.indexOf(planetUserSelected) !== -1) will give you back the object you're looking for, and you can console.log() that value and go from there.

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Javascript: Cant fetch value of input number box

Hello almighty internetz!
Im totally new on javascript, and i cant get the script to fetch numbers from input boxes, plus the sums together and write it out.
Have been sitting on Google for an hour now, so im asking you guys/girls for help!
http://jsfiddle.net/heWM2/5/
<form action="" id="brod">
<p>Pris per kartong
<input name="Prisperkartong" type="number" id="priskart" name="pris">
</p>
<p>Antal kartonger i leverans
<input name="Kartongilev" type="number" id="kartilev">
</p>
<input type="button" onClick="calculateTotal()" value="Räkna">
<div id="print"></div>
</form>
And the Javascript:
function getPrisperkartong() {
var Prisperkartong = parseInt(document.brod.priskart.value, 10);
if (isNaN(Prisperkartong)) return;
document.bord.priskart.value = Prisperkartong;
}
function getKartongilev() {
var Kartongilev = parseInt(document.brod.kartilev.value, 10);
if (isNaN(Kartongilev)) return;
document.bord.kartilev.value = Kartongilev;
}
function calculateTotal() {
var total = getPrisperkartong() + getKartongilev();
var divobj = document.getElementById('print');
divobj.style.display = 'block';
divobj.innerHTML = "Pris $" + total;
}
If you are accessing the input boxes through the form, you need to use the name field to identify the form as well as the input boxes. Your get functions should also return the value, not assign it back to the original input box. See this updated fiddle for a fixed, working example.
http://jsfiddle.net/heWM2/6/

Categories

Resources