I am trying to build a simple javascript calculator that will ask user to input name and it will display a number according to input, each letter in string will have a value like a=1 and b=2. If we insert acb in input it should display abc=1+2+3 =6.
thanks
<input type="text" id="myText" value="">
<button onclick="myFunction()">Try it</button>
<p id="calc"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("calc").innerHTML = x;
}
</script>
Try this, it uses a simple a=1 to z=26 code. If a special character or number is entered, they are treated as 0. This does work for uppercase and lowercase letters.
function myFunction() {
var x = document.getElementById("myText").value;
var total = 0;
for (var i = 0; i < x.length; i++) {
var temp = x.toLowerCase().charCodeAt(i) - 96;
if ((temp > 0) & (temp < 27)) {
total = total + temp;
}
}
document.getElementById("calc").innerHTML = total;
}
<input type="text" id="myText" value="">
<button onclick="myFunction()">Try it</button>
<p id="calc"></p>
This question already has answers here:
how to append to a object with innerHTML
(7 answers)
Closed 6 years ago.
The function will display all the even numbers between starting number and ending number based on the step value.
For example, if I enter 1, 20, and 3.
I should have 4, 10, and 16 as even number.
I need to push all the numbers inside evenNum array into #result span.
Currently it seems to only display the last even number inside the array.
Further more, if I would like to display all even number in vertical line, how do I do it?
https://codepen.io/anon/pen/wgwaey
<body>
<div class="container">
<h1>Sample</h1>
</div>
<div class="container">
<label>Starting Number: </label>
<input id="startingNum" type="text">
<br>
<label>Ending Number: </label>
<input id="endingNum" type="text">
<br>
<label>Step: </label>
<input id="step" type="text">
<br>
<button onclick="playButton()" id="play">Display Evens</button>
</div>
<div class="container">
<p>Here are the even numbers between <span id="startNum"></span> and <span id="endNum"></span> by <span id="stepNum"></span>'s:</p>
<span id="result"></span>
</div>
</body>
JS:
<script>
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
}
}
</script>
The problem is here:
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
You need to move this out of the while loop and change it to
document.getElementById("result").innerHTML += ' ' + evenNum[i];
// ^ add to existing
Or, more simply, delete the for loop and put this after the while loop:
document.getElementById("result").innerHTML = evenNum.join(' ');
The mistake above is that you're continuously reseting the result's inner HTML, so the last element of even num is the only one displayed. Also, you don't need to be updating result inside of your while loop, you can do it once you're done looking. Try this out!
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
}
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML += "<p>" + evenNum[i] + "</p>";
}
}
Greetings I am trying to do a simple swap by comparing 2 numbers from a string and the switching the higher number to the left. I am using a while loop to make the changes but i get a TypeError: input is not a function chartest.html:32:4
I do not see what i am doing wrong can anyone look at my code. Here is a look at my code.
<body>
<form>
Enter numbers to be sorted from into high to low
<input id="num" type="text" value="" >
<br>output<input id="forTest" type="text">
<br><button type="button" onclick="calc(); return false" >Enter</button>
<input type="reset">
</form>
<p id="what"></p>
<script>
function calc()
{
var input = document.getElementById("num").value;
var wordlength = input.length;
var i = 0;
while(i < wordlength -1)
{
a = input.charAt(i);
b = input.charAt(i+1);
if(a < b)
{
input(i) = b;
input(i+1) =a;
}
i++;
}
alert(input);
//document.getElementById("forTest").value = testString;
//document.getElementById("what").innerHTML = testString;
}
</script>
</body>
Functional programming is your friend :)
var input = document.getElementById("num").value;
var arrayOfChars=input.split(""); //Or split by comma or whatever
var sortedArrayOfChars=arrayOfChars.sort(sortingFunction);
function sortingFunction(a,b){return a-b;}
Or, as a 1 liner...
input.split("").sort(function(a,b){return a-b;})
The title is the question in mind.
Here is what I have so far:
html>
<head>
<title> New Document </title>
</head>
<script type = "text/javascript">
var i;
var elmt = nums[10];
var ask = prompt("Please enter 10 numbers");
var sum = 0
for(var i =0, i< elmt.length; i++;):
sum += parseInt(elmt[i], 10);
var avg = sum/elmt.length;
document.write("The sum of all the elements is: " + sum + " The average is: " +avg);
<body>
</body>
</html>
I'm not really sure what I'm doing to be honest. I tried researching arrays and this questions and similar ones so I can try to learn the syntax but to no avail. I'm practicing this on my own to try and learn. Please don't bash, I'm not asking anyone to do this FOR me, hints would be ok. I'm not some teenager endlessly dumping in code and hoping the internet does my homework.
EDIT1:
<html>
<head>
<title> nums </title>
</head>
<script type = "text/javascript">
var sum =0;
var belowAvg = 0;
var num = new Array(10);
var sum = 0
var i;
for(i = 0; i<10; i++;):
{
num[i] = eval(prompt("Enter a number"));
sum = sum + num[i];
}
avg = sum/10;
for (i=0; i<10; i++)
{
if ( num[i] < avg)
{
belowAvg++;
}
}
alert ("average is" + avg);
alert (belowAvg + "numbers are less than the average");
</script>
<body>
</body>
</html>
EDIT2:
Ok, now I'm extremely lost. Everyone had good answers and all but my understanding isn't enough to apply any of them unfortunately. I've been playing around with all suggestions and I'm still lost. Can anyone show me an example maybe? I didn't want my hand to be held, but....
You're almost there, but you're only prompting once and placing the input in to a variable. You need to prompt 10 times if you want 10 numbers (otherwise you need to parse the input and extract 10 numbers from it).
Assuming you wanted a few methods of populating elmt through ask (here i use input instead of ask and nums instead of elmt--but we're talking minor semantics):
Method one, prompt 10 times:
// initialize array with 10 elements
var nums = new Array(10);
// iterate over each element and prompt for value
for (var i = 0; i < nums.length; i++){
var input = prompt('Enter number ' + (i + 1) + ' of ' + (nums.length + 1));
// place value (as a number) into the array
nums[i] = new Number(input);
}
/* sum/average code */
Method two, prompt once and String.prototype.split:
// initialize array with 10 elements
var nums = new Array(10);
// prompt for 10 numbers
var input = prompt('Enter ' + (nums.length + 1) + ' numbers separated by commas:');
var values = input.split(',');
// check we have the right amount
if (values.length == nums.length){
// iterate over the values
for (var i = 0; i < nums.length; i++){
// place the input (as a number) into the array
nums[i] = new Number(values[i]);
}
}
/* sum/average code */
Method three, input boxes:
<script>
function average(){
// initialize array with 10 elements
var nums = new Array(10);
// iterate over the elements
for (var i = 0; i < nums.length; i++){
// grab <input> based on id attribute
var input = document.getElementById('num' + i);
// insert the value (cast as a number) in to the array
nums[i] = new Number(input.value); // case to number
}
/* sum/average code */
}
</script>
<p>Enter 10 numbers:</p>
<input type="text" id="num0" />
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="text" id="num3" />
<input type="text" id="num4" />
<input type="text" id="num5" />
<input type="text" id="num6" />
<input type="text" id="num7" />
<input type="text" id="num8" />
<input type="text" id="num9" />
<button onclick="average()">Click to average</button>
I need to use a for loop to add 2 random letters to the string inputed into the text box and returned in the encrypted string box when the button is clicked.
So, for example, if cat was inputted it could return like cynarwtpp. I am new to for loops and unsure how to proceed from here, I need to use a for loop that will cycle through the alphabet array. any help would be greatly appreciated.
Javascript:
<script type="text/javascript">
var uncoded_array = uncoded.split("");
var coded_str = "";
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
</script>
Html:
<form action="">
Enter a String: <input type="text" name="uncoded" ></br>
<input type="button" value="cipher" onClick=document.forms[0].coded.value= ></br>
Encrypted String: <input type="text" name="coded" ></br>
This is what I would do
html
Enter a String: <input type="text" id="uncoded" />
<input type="button" value="cipher" onclick="cypher(); return false;" />
Encrypted String: <input type="text" id="coded" />
js
function cypher() {
var coded = document.getElementById('coded');
var uncoded = document.getElementById('uncoded');
coded.value = uncoded.value.split('').map(function (char) {
return char + randomLetter() + randomLetter();
}).join('');
}
function randomLetter() {
return Math.random().toString(36).replace(/[^a-zA-Z]/gi, '')[0];
}
Here is a simple approach.
1) From this answer I learned to pick random element from array.
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
In your case 2 random letter from array.
2) In the for iteration, I have taken a string length and used to add the random element after each letter and concatenated together.
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
var original = "cat";
var encrypted = "";
for (var i=0; i<original.length; i++ ) {
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
encrypted += original[i] + item1 + item2;
}
alert(encrypted);
JSFiddle
Here's a simple function that performs the string operation. Just feed it the value of the first form input, and dump its result into the second form input.
function cipher(str) {
var rand,
output = '',
chars = 'abcdefghijklmnopqrstuvwxyz';
for (i=0; i<str.length; i++) {
output += str[i];
for (j=0; j<2; j++) {
output += chars[Math.floor(Math.random() * chars.length)];
}
}
return output;
}
cipher('cat');