Using user input for javascript function (for loop) - javascript

I have a basic js function that connects to my html file. I want the user to input a number and then the function will count up to that number. As it counts it will display a circle with each number. So, input 3 and you'll see three circles counting 1, 2, 3 horizontally on the page.
When I call the function and hard code an input like:
display(9)
it works fine.
I console log my user input, I console log as I loop through and it's counting just fine, but for some reason,
const button = document.getElementById("button");
const main = document.querySelector("main");
let number = "";
function display(num) {
for (let i = 1; i <= num; i++) {
console.log("in the loop " + i);
number += `<div>${i}</div>`;
}
}
button.addEventListener('click', () => {
let input = parseInt(document.getElementById("input").value);
console.log(input);
display(input);
});
document.getElementById("display").innerHTML = number;
<h1 class="h1">Test Form</h1>
<input class="input" id="input" type="text" />
<input type="button" id="button" value="Enter" />
<p class="display" id="display"></p>
it won't display anything using user input.
My code is below. Thoughts? And thank you for the help!

You just add the following statements to the end of display function to make it work.
let displayDiv=document.getElementByI("display");
displayDiv.innerHTML=number;

Related

Javascript Arrays. Adding, subtracting and totaling

I'm having a little trouble with an assignment a teacher dished out to my class involving javascript arrays. What they essentially want us to do is to create sort of cart / calculator hybrid that allows users to input numbers, store them and array and display those numbers on the webpage, then be able to either add them together for a total or reset them and start over.
I think I more or less know how to make a reset button, and I believe I've figured out how to add items to the array efficiently enough, but I'm kinda stumped on how to show those items on an html page and how to add them together to make and show a total. Any help would be appreciated, I'm kinda new at this and so far the instructions from our source material are a bit vague and hard to understand, at least for me!
So far I have some simple html for the input field and an "add number" button which will add the input field to the array (I will limit it to numbers only later and will).
<form onsubmit="return userNumber()">
<p>Number:</p>
<input type="text" id="box" />
<br>
<input type="button" value="Add Number" />
<input type="button" value="Calculate" />
<input type="button" value="Reset" />
</form>
I've no code yet for the Calculate or Reset button, but for the Add Number button which does seem to work properly when I bring up the console, I just need it to also display on the webpage. Here's what I have for that.
var numbers = [];
function userNumber() {
boxvalue = document.getElementById('box').value;
numbers.push(boxvalue);
console.log(numbers);
return false;
}
I've attached an image of what our teacher showed us, they want us to make it only similar in function, looks are not as important.
Once again, thank you to anyone who can assist, I'm very lost on where to go from here!
First, give them all an id. It's a lot easier to work with them when they all have the "names". And then you can easily handle the events (clicks in this example).
Notice, when you click on the "Add" button, before push you need to use parseInt(string, base) since input.value is a string, and + operator is concatenation for string, not addition. Like sum += numbers[i]; below.
And there is a couple of protection for corner cases when you click the "Calculate" button with an empty numbers array for example.
var numbers = [];
var boxInput = document.getElementById("box");
var addBtn = document.getElementById("add");
var calculateBtn = document.getElementById("calculate");
var resetBtn = document.getElementById("reset");
var allNumbers = document.getElementById("all-numbers");
var calculatedNumbers = document.getElementById("calculated-numbers");
addBtn.addEventListener("click", function() {
if (boxInput.value.length > 0) {
numbers.push(parseInt(boxInput.value, 10));
boxInput.value = "";
}
allNumbers.innerHTML = numbers.join(" ");
});
calculateBtn.addEventListener("click", function() {
if (numbers.length === 0) {
return;
}
for (var i = 0, sum = 0; i < numbers.length; i++) {
sum += numbers[i];
}
calculatedNumbers.innerHTML = numbers.join(" + ") + " = " + sum;
});
resetBtn.addEventListener("click", function() {
numbers = [];
boxInput.value = "";
allNumbers.innerHTML = "";
calculatedNumbers.innerHTML = "";
});
<p>
<label for="box">Number:</label>
<input id="box" type="number" />
</p>
<p>
<input type="button" id="add" value="Add Number" />
<input type="button" id="calculate" value="Calculate" />
<input type="button" id="reset" value="Reset" />
</p>
<h3>Numbers added:</h3>
<p id="all-numbers"></p>
<h3>Sums of numbers added:</h3>
<p id="calculated-numbers"></p>

Nothing appears on console in chrome,taking information from form

I'm creating a simple string reverse project.
I want the user to enter input, then that input will be displayed below the text box in reverse order.
<form id = "frm1">
<input type="text" id="userInput"=> give me input</input>
<button onclick="strRev()">Submit</button>
</form>
<script type="text/javascript">
function strRev(str){
str = document.getElementById("userInput").toString().value;
console.log(str);
var originalStr = str.split("");
console.log(originalStr);
var finalArray = [];
var j = 0;
for(i = originalStr.length-1; i >= 0; i--){
finalArray[j] = originalStr[i];
j++;
}
for(k = 0; k <finalArray.length; k++){
document.write(finalArray[k]);
}
}
</script>
When pressing submit, the information in the box is what should be reversed
Nothing happens on submit and nothing appears in console to debug.
Try the below code:
str = document.getElementById("userInput").value;
onclick="strRev()"
and you are calling
function strRev(str) // function with one argument, must be showing error in console
Add type="button" in your button input, that way the form won't refresh
<button type=button onclick="strRev()">Submit</button>
You will probably be able to continue solving your other problems after that.
You have an error in your html here <input type="text" id="userInput"=>
it should be <input type="text" id="userInput">
also fetching the value of input should be like this
str = document.getElementById("userInput").value;
After applying these changes you will see the output in console

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/

How to add multiple input boxes with different names

I am trying to make a button to add another input box every time it is clicked but I also want it to add an increasing number the end of the input name. I have this code to add more inputs.
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"file\" name=\"photo\" />";
}
</script>
What can I do to make it so that every time a new form is added it will add a higher number to the end of name="photo" so that I can process images with my php script correctly?
default the form is:
<input type="file" name="photo">
but I would like to add a number to the end of photo every time a new input is made to have an output like this.
<input type="file" name="photo">
<input type="file" name="photo2">
<input type="file" name="photo3">
<input type="file" name="photo4">
etc
You can use [] in your form name, then your php script will automatically convert those inputs into an array, that way you don't even have to worry about appending numbers anymore.
<input type="file" name="photo[]">
If you want to do it using javascript, easiest way is to have a variable that keeps track of the number of inputs
var inputNumber = 0;
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"file\" name=\"photo\"" + inputNumber + " />";
inputNumber++;
}
Declare a count and initialize it to 0, then increase it in every call.
<script type="text/javascript">
var count=0;
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += '<input type=\"file\" name=\"photo\"'+count+' />;
count++;
}
</script>
andeas's answer is probably best for this specific situation. But in general if you want a counter that will increase every time a function is called, try:
(function {
var counter = 0;
window.myfunction = function() {
// do stuff, use counter if needed
counter++;
}
})();
counter can be treated as if it were a static variable in this context.

Categories

Resources