1

I made an app that assigns value to letters A-Z = 1-26 and sums them. How can i get the value of each letter from the input field? For example if i type 'bb' it will output b(2)+b(2) = 4 in span with id 'a'

https://codepen.io/anon/pen/pOvNXd

function myFunction() {
  //code
var alp = {a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, k:11, l:12, m:13, n:14, o:15, p:16, q:17, r:18, s:19, t:20, u:21, v:22, w:23, x:24, y:25, z:26, ' ':0, '"':0, "'":0, '!': 0, '#':0, '$':0, '%':0, '(':0, ')':0, '+':0, '-':0, '*':0, '/':0, '=':0, '_':0, '@':0, '?':0, '&':0, '.':0, ',':0, ':':0, ';':0}

//starting value
var str = document.getElementById("txt").value;
var n = str.length;
var total = 0;
  
//counter
for (var i = 0; i < str.length; i++)
  total += alp[str[i]]

//output
document.getElementById("res").innerHTML = total;
document.getElementById("a").innerHTML = n;
}
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
</head>

<body>
  <div id="wrapper">
    <center>
      <h1>Task</h1><br>
      <input type="text" name="fname" id="txt" style="width: 500px; font-size: 125%" size="60px" value="" placeholder="Type something..." oninput="myFunction()">
      <br><br>
      <p style="color: RGB(0,186,0)">Sum</p>
      <span id="res" style="color: RGB(0,186,0)">0</span>
      <br>
      <p id="a">0</p>
    </center>
  </div>
</body>
</html>
stanislav
  • 25
  • 1
  • 6
  • 1
    please add the relavant part/s to the question. [mcve] – Nina Scholz Aug 21 '18 at 17:19
  • 1
    You're missing `i++` in the `for` loop, so you have an infinite loop. – Barmar Aug 21 '18 at 17:23
  • It is unclear what you are asking, what value do you want to get? Also you refer to some `span`, if so please provide the neccesary markup. – Olga Aug 21 '18 at 17:25
  • I want when i type in the input field a word to get the value of each letter and output the values in the second span with id 'a' For example if i type bb it will output 'b(2)+b(2)' = 4 in the span with id 'a' The n var was just a test – stanislav Aug 21 '18 at 17:30
  • 2
    I think you should update the question with the provided explanation, as it is quite confusing at the moment. Another tip is to get rid of `id="a"` and instead call it `id="expression-and-result"` or similar, the code will immediately become self explanatory in this aspect. You will forget what `a` was in a month or earlier. – Olga Aug 21 '18 at 17:40

4 Answers4

0

Here's my code, so I've done some changes.

  1. As @Barmar mentioned, you've missed the i++ in the for loop which makes it infinite.
  2. I've added .split('') after you received the text from the input, which turns it into an array, where later used in your code str[i].

Edit:

After searching around StackOverflow, I've found this answer:

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

So even though you're code can directly use str[i], I'll still prefer changing it into an array, in case you'll need to act it as an array (edit or something like that) later on.

function myFunction() {
  //code
  var alp = {a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, k:11, l:12, m:13, n:14, o:15, p:16, q:17, r:18, s:19, t:20, u:21, v:22, w:23, x:24, y:25, z:26, ' ':0, '"':0, "'":0, '!': 0, '#':0, '$':0, '%':0, '(':0, ')':0, '+':0, '-':0, '*':0, '/':0, '=':0, '_':0, '@':0, '?':0, '&':0, '.':0, ',':0, ':':0, ';':0};

  //starting value
  var str = document.getElementById("txt").value.split('');
  var n = str.length;
  var total = 0;
  var result = "";

  //counter
  for (var i = 0; i < str.length; i++) {
    total += alp[str[i]];
    result += str[i] + "(" + alp[str[i]] + ") + ";
  }
  result = result.substr(0, result.length - 2) + " = " + total;
  //output
  document.getElementById("res").innerHTML = result;
  document.getElementById("a").innerHTML = "Total: " + total;
}
body {
  margin: 0px;
  padding: 0px;
  background-color: white;
  color: black;
}

body,
input {
  font-family: 'Roboto Condensed', sans-serif;
}

header input::-webkit-input-placeholder {
  color: rgba(255, 255, 255, 0.8)
}

#txt {
  color: rgba(0, 0, 0, 0.8);
  border-radius: 1%;
  transition: all 200ms ease-out;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
}

#txt:hover {
  box-shadow: 0 0 6px rgba(35, 173, 278, 1);
}

#txt:focus {
  box-shadow: 0 0 6px rgba(35, 173, 278, 1);
}

#wrapper {
  margin: 0px padding: 0px;
}
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
</head>

<body>
  <div id="wrapper">
    <center>
      <h1>Task</h1><br>
      <input type="text" name="fname" id="txt" style="width: 500px; font-size: 125%" size="60px" value="" placeholder="Type something..." oninput="myFunction()">
      <br><br>
      <p style="color: RGB(0,186,0)">Sum</p>
      <span id="res" style="color: RGB(0,186,0)">0</span>
      <br>
      <p id="a">0</p>
    </center>
  </div>
</body>

</html>
Andrew.Wolphoe
  • 420
  • 5
  • 18
0

From your last comment I believe that you might want something similar to this:

const cap = (n, min, max) => Math.max(min, Math.min(n, max));
const getNumValue = char => cap(char.charCodeAt(0) - 96, 1, 26);

function myFunction() {
  const str = document.getElementById("txt").value;
  const total = str.split('').map(getNumValue).reduce((a, b) => a + b, 0)
  const n = str.split('').map(v => `${v}(${getNumValue(v)})`).join(' + ');

  document.getElementById("res").innerHTML = total; 
  document.getElementById("a").innerHTML = n;
}
<h1>Task</h1><br>
<input type="text" name="fname" id="txt" style="width: 500px; font-size: 125%" size="60px" value="" placeholder="Type something..." oninput="myFunction()">
<br><br>
<p style="color: RGB(0,186,0)">Sum</p>
<span id="res" style="color: RGB(0,186,0)">0</span>
<br>
<p id="a">0</p>

You can use the logic you already have to calculate your total, I just didn't like the big object. Be careful though, this resolves values outside (a-z) with different values.

Aramil Rey
  • 3,387
  • 1
  • 19
  • 30
0

Why don't you use ASCII values for this. You can subtract 64 from ASCII value of all the capital alphabets and assign value 0 to any character having ASCII value outside the range 65-90.

To get ascii value use "A".charCodeAt(0) which will return 65.

  • 2
    I believe this is better suited as a comment rather than an anwser. – Olga Aug 21 '18 at 18:07
  • Also, it takes a lot of explaining to get from the UTF-16 unit codes ([charCodeAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt)) that JavaScript uses to ASCII. – Tom Blodget Aug 21 '18 at 19:28
0

So to build up your desired output you can to use string concatenation:

  1. Split the string into an array of it's charachters
  2. Go over each element in the array and modify it to be the desired expression with map method.
  3. Join the modified elements with +
  4. Concatenate with the result and output it to the dom

    var expression = str.split('')
        .map(function (currentLetter) {
            return currentLetter + '(' + alp[currentLetter] + ')';
        })
        .join(' + ');
    
    var expressionAndResult = expression + '=' + total;
    
Olga
  • 1,648
  • 1
  • 22
  • 31