Javascript random generator - javascript

I created a random number generator in javascript whose values are in an array.
The code is that one
function GetValue()
{
var names= new Array(1,2,3,4,5);
var random = names[Math.floor(Math.random() * names.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}
<p>number generator</p>
<form class="form">
<div class="form-group">
<input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default" />
<p id="message"></p>
</div>
</form>
I'd like to know if it is possible to give a different text in the p tag according to the number generated by the button.
Thanks very much and sorry if there is any english error

Just give the element an identifier, select it in your code and change the value according to your 'random' value:
function GetValue() {
var names = [1,2,3,4,5];
var random = names[Math.floor(Math.random() * names.length)];
var messageContainer = document.getElementById("message");
var headline = document.getElementById("headline");
if (random <= 2) {
headline.innerHTML = 'Hamburger (' + random + ')';
} else {
headline.innerHTML = 'Fish (' + random + ')';
}
}
<p id="headline">number generator</p>
<form class="form">
<div class="form-group">
<input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default"/>
<p id="message"></p>
</div>
</form>

I'm not sure of what you want, but If you want to randomly select from a string:
function GetValue(){
var names= new Array(1,2,3,4,5);
var texts = ["foo", "bar", "baz", "foo2", "barbaz"];
var random = names[Math.floor(Math.random() * names.length)];
//alert(random);
document.getElementById("message").innerHTML = texts[random - 1];
};
here is the fiddle: https://jsfiddle.net/x2zkph3x/

If your question is "How to display a randomly selected text when clicking a button", this is the answer:
var generator = document.getElementById('generator'),
message = document.getElementById('message'),
strings = ['first', 'second', 'third'];
generator.addEventListener('click', function(event) {
message.textContent = strings[Math.random() * strings.length | 0];
});
<input type="button" id="generator" value="Generate">
<p id="message"></p>

Related

The calculator won't display the right results

I would like to ask a bit of help. I was creating a simple calculator. The problem is my calculator displays the same results everytime. The addition would display nothing, the subtraction and multiplication would display 0, and the division and modulo would display NaN. Here is my code:
let a = document.getElementById("num1").innerHTML;
let b = document.getElementById("num2").innerHTML;
function addFunction() {
let add = a + b;
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = a - b;
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = a * b;
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = a / b;
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = a % b;
document.getElementById("result").innerHTML = modulo;
}
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1">
<input id="num2">
<br>
<br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
You should get values of input not innerHTML like this
var a = document.getElementById("num1").value
var b = document.getElementById("num2").value
And then convert it to number like this
a = parseFloat(a)
b = parseFloat(b)
You need to do this:
let a = parseFloat(document.getElementById("num1").value);
let b = parseFloat(document.getElementById("num2").value);
You need .value to get the text of the input field, this will return a string so you also need to use the Unary Plus (+) to convert it to a number:
+document.getElementById("num1").value;
+document.getElementById("num2").value;
Since the content of both input boxes change throughout the program, you would need to run the lines above mulitple times to get the updated content. You can do this with functions:
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
To prevent the user from entering characters that aren't numbers you can also set the input type:
<input id="num1" type="number">
<input id="num2" type="number">
Full code:
<html>
<body>
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1" type="number">
<input id="num2" type="number">
</br>
</br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
<script>
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
function addFunction() {
let add = getA() + getB();
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = getA() - getB();
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = getA() * getB();
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = getA() / getB();
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = getA() % getB();
document.getElementById("result").innerHTML = modulo;
}
</script>
</body>
</html>

Is there a way to modify variable inside the <body> tag as it's being displayed?

I am tring to implement a simple program that takes an integer and displays 10 🐸 themed times tables when the button is clicked. The idea to multiply the integer by the number of frogs and display the correct answer
function doCalculations() {
//Get the input field value
var userInput = document.getElementById("userInput");
var timestable = userInput.value;
}
<h1>Enter a positive integer to generate FROG-timestable: </h1>
<input type="text" size="10" id="userInput"/>
</br>
<button onclick="doCalculations();">
Generate FROG-timestable:
</button>
</br>
<h2>
+timestable * 🐸 =
</br>
+timestable * 🐸🐸 =
</br>
+timestable * 🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸🐸🐸🐸🐸 =
</br>
+timestable * 🐸🐸🐸🐸🐸🐸🐸🐸🐸🐸 =
</h2>
I hope something like this is what you are trying to achieve.
Check the below snippet and get back to me in case if you require any clarifications.
I used jQuery to achieve it easily. You can do this with native JS also.
function doCalculations() {
//Get the input field value
var inputValue = $('#userInput').val();
var item = "";
for(var i=1; i<=10; i++) {
var frog = "";
for(var j = 0; j<i; j++) {
frog += "🐸";
}
item += "<h2>"+ inputValue + " * " + frog + " = "+ i*inputValue + "🐸</h2>"
}
$('#frog-table').html(item);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Enter a positive integer to generate FROG-timestable: </h1>
<input type="text" size="10" id="userInput"/>
<button onclick="doCalculations();">
Generate FROG-timestable:
</button>
<section id="frog-table">
</section>
This will work as you expected.
<script>
function doCalculations(){
//Get the input field value
var userInput = document.getElementById("userInput");
var timestable = userInput.value;
const cars = [];
cars.length = timestable;
var container = document.getElementById("demo");
for (var i = 0; i < cars.length; i++) {
container.innerHTML += '<span >&#128056</span>';
}
}
</script>
<body>
<h1>Enter a positive integer to generate FROG-timestable:</h1>
<input type="text" size="10" id="userInput"/>
</br>
<button onclick="doCalculations();">Generate FROG-timestable</button>
<div id="demo"></div>
</body>
I think this will help you

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

Auto calculation occurs on previous value

i have a function that increments a number, takes the total and multiplies it by a price. However, when I click the button that increments for the first time it doesn't do anything. I click the button a second time and it works. However if I then click the button that decreases, then it does the previous function (e.g. adding) then pressing it a second time will decrease the value.
I understand that the onClick="myFunction()" may be in the wrong place, however I don't know where to put it. I want the total to be calculated automatically. A demo can be found at http://alpha.kentishtours.co.uk/destinations/bruges.php
The function that takes the value and multiplies it and calculates the total.
function myFunction()
{
var a = document.getElementById('adult').value;
z=39;
x=a*z;
var c = document.getElementById('child').value;
if(a >= 1) {
a=+30; }
else {
a=+39; }
b=c;
c=a*b
d=x+c
document.getElementById("total").innerHTML=d;
document.getElementById("value").value = d;
}`
These are the buttons that increment the number and call the function to calculate.
<div class="calculator">
<div class="calculator-submodule input-group">
<h4>Adult (12+)</h4>
<button class="btn theme-btn" id="decrease" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="adult" value="1" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increase" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule input-group">
<h4>Child (2-11)</h4>
<button class="btn theme-btn" id="decreasec" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="child" value="0" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increasec" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule">
<span class="pound">£</span>
<span id="total">39</span><span class="pound">.00</span>
</div>
You have functions in your increment.js script that change the value of the input after you get them in "myfuntion". You need to calculate the prices after the values are changed.
So first you should remove the lines below from this file:
http://alpha.kentishtours.co.uk/assets/scripts/increment.js
$("#increase").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())+1);
});
$("#decrease").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())-1);
});
$("#increasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())+1);
});
$("#decreasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())-1);
});
Also remove the onClick="myFunction()" attribute in your HTML form.
Then change all your myFunction script to this:
var adult = $('#adult'),
child = $('#child'),
total = $('#total'),
value = $('#value'),
increase = $('#increase'),
decrease = $('#decrease'),
increasec = $('#increasec'),
decreasec = $('#decreasec');
var calulate_price = function(a, c){
var p1 = 39,
p2 = 30,
PA = a * p1,
PC, d;
if(a >= 1) PC = c * p2;
else PC = c * p1;
d = PA + PC;
total.text(d);
value.val(d);
};
increase.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(++a);
calulate_price(a, c);
});
decrease.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(--a);
calulate_price(a, c);
});
increasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(++c);
calulate_price(a, c);
});
decreasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(--c);
calulate_price(a, c);
});
Everything working: http://jsbin.com/ohUniCa/2/edit?js,output

Categories

Resources