How to take input at terminal in JavaScript - javascript

How can I take input at terminal
Here the first line contain an integer (the size of my array).
The second line contains integers that describe array 's elements.
I used
window.prompt()
but it take input only in browser. How can I take input in terminal
function arrayAction(A, N) {
var temp = []
var r = window.prompt(N)
for (var i = 0; i < r; i++) {
temp.push(window.prompt(A))
temp.reverse();
}
console.log(temp)
}
arrayAction()

if you want to take input you should use this small html and javascript code
var a = document.getElementById("hello").value;
alert(a);
<input id="hello" type="text">
<span="hi"your number is</span>
<p></p>
var num=document.getElementById("hello")
var te=document.getElementById("out")
function demo(){
te.innerHTML=num.value;
//document.write(num.value);
}
<input id="hello" type="number" >
<button onclick="demo()">Click me to get your input number</button>
<br>
<span id="hi">your number is</span>
<p id="out"></p>

Related

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>

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>

How to get a <input> id number into a var (Math)

I got a input number into a var. I subtracted it to a number.
Thank you vicodin for helping me! I fixed it and it works! (I changed names for my program)
<!DOCTYPE html>
<html>
<body>
<p></p>
<span><input type="number" id="guess1"><p id="g1s"></p></span>
<input type="button" onclick="Calculate()" value="Calculate">
<script>
function Calculate() {
var GuessCon1 = document.getElementById("guess1").value;
var GuessCon1sub = GuessCon1 - 500;
document.getElementById("g1s").innerHTML = GuessCon1sub;
}
</script>
</body>
</html>
You assigned a string "numb1" to variable g. If you want to get the value of the input, you need to find that element (e.g. with document.geElementById method) and take a value from it.
Also, you want to trigger calculation, for example by a button click. I added a code in a snippet, you can run it and play around with it to get the idea.
var button = document.getElementById("substract")
button.onclick = function() {
var g = document.getElementById("numb1").value
var a = 578;
var x = g - a;
document.getElementById("demo").innerHTML = x;
}
<input type="number" id="numb1">
<input type="submit" id="substract">
<p id="demo"></p>
Related links:
Input Text value Property
onclick event

Re-feeding a variable into a looped function

I'm attempting to make a simple program for encoding things in base64 multiple times (not really for any particular reason, just more as an example and practice). I've been having quite a bit of trouble though, it could be because I've not had enough (or possibly had too much) coffee.
I can't seem to figure out how to refeed my variable (text) back into the function that encodes it until i is equal to times
Any assistance with this would be appreciated!
<html>
<head>
<script>
function encodeThis(text,times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
</script>
</head>
<body>
<b>Text to Encode</b><br/>
<input type="text" id="encode"><br/>
<b>Number of Times to Encode (Integers Only)<br/>
<input type="text" id="times">
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">
</body>
</html>
Would I need to put a function inside of that function to refeed the variable in?
You need to assign the result of the encoding back to the variable.
function encodeThis(text, times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
But in terms of the overall code in your example you also need to actually get the text from the #encode and the #times elements and fix the syntax error in the for loop.
So
function encodeThis(text, times) {
var toEncode = text.value, // read the value from the encode input element
numTimes = parseInt(times.value, 10); // read the value from the times element and convert to number
for (var i = 0; i < numTimes; i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
<b>Text to Encode</b><br/>
<input type="text" id="encode" /><br/>
<b>Number of Times to Encode (Integers Only)</b><br/>
<input type="text" id="times" />
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">

Displaying new input value (adding spaces)

This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

Categories

Resources