1
  • Firstly, i wanna assign numbers to all alphabets like this:a=1,b=2,c=3,d=4 etc.

  • Secondly, I want to create an input field and submit Button.

  • Thirdly, when I enter alphabets on that input field, (eg: abcd it shows 1234 because i already mentioned above, a=1, b=2, c=3, d=4).

  • And last, I wanna to add them (eg: I entered "abcd" and output is 1234 and add them.)Final Output for abcd is 1+2+3+4 =10.

    import React,{useState} from 'react' import "../node_modules/bootstrap/dist/css/bootstrap.min.css"

const Data = () => { const [data, setData] = useState({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})

const changeHandler = e => {
    setData({...data,[e.target.name]:[e.target.value]})
   
   
}
const submitHandler=e=> {
    e.preventDefault();
    
  }
return (
<div>
    <form onSubmit={submitHandler}>
    <input type="text"onChange={changeHandler}/><br/>
    <button className="btn btn-primary"onClick={()=>setData(console.log(data))}>Click</button><br/>
    </form>


</div>

) }

export default Data

mvsr cm
  • 29
  • 5
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 01 '22 at 05:31
  • Is it necessary to use a useState? You can simply convert the letters to their ASCII number and do some math to achieve what you are looking for. – Michael Boñon May 01 '22 at 05:38
  • `const numbers = {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};` – Beki May 01 '22 at 05:39
  • @MichaelBoñon : no sir, its not necessory.(useState) can you please write code and send me sir, asking help from you! – mvsr cm May 01 '22 at 05:42
  • @Beki : Thanq so much sir – mvsr cm May 01 '22 at 05:43
  • Kindly share what code has already been developed thus far and if any error/s or problem/s or issue/s being faced. – jsN00b May 01 '22 at 05:50
  • 1
    @jsN00b ok sir will share now... – mvsr cm May 01 '22 at 06:03
  • Have added an answer @mvsrcm. One does not need to list down all 26 letters and map them. JavaScript `String#charCodeAt()` allows us to get a character code. For example lowercase `a` has a code 97. We can use this to convert user-input text into numbers. – jsN00b May 01 '22 at 06:38

2 Answers2

2

you can do something like this

const dictionary = Object.fromEntries(Array(26).fill('a').map((s, i) => [String.fromCharCode(s.charCodeAt() + i), i + 1]))


export default function App() {
  
  const [string, setString] = useState('')
  const [numbers, setNumbers] = useState([])
  const [total, setTotal] = useState(0)

  const changeHandler = (e) => {
    setString(e.target.value)
  }

  useEffect(() => {
      setNumbers(
        string.toLowerCase().split('').map(c => dictionary[c])
      )
  }, [string])

  const calculateTotal = () => {
    setTotal(numbers.reduce((a, b) => a + b, 0))
  }
  
  
  return (
    <div className="App">
    <div>{numbers.join(' ')}</div>
    <input type="text" onChange={changeHandler} value={string}/><br/>
    <button className="btn btn-primary"onClick={calculateTotal}>Click</button><br/>
    {total > 0 && <div>the total is {total} }
    </div>
  );
}

R4ncid
  • 6,944
  • 1
  • 4
  • 18
  • sir thank you so much for spending your valuable time sir you done a great job sir. this snippet is also worked for me. i owe you sir . thank you so much sir. – mvsr cm May 01 '22 at 14:00
  • Sir, Your code is working great. but when i clicked on that button, it shows the answer in console. can you please set the answer below of that button, sir please. waiting of your answer – mvsr cm May 02 '22 at 10:46
  • Thank you so much sir... its working by erasing some errors in code. excellent job sir...love from india – mvsr cm May 02 '22 at 11:22
  • sir, last question.. what if i wanna to assign a random numbers to the alphabets. please sir, if you can please share your code sandbox link sir.. love from india – mvsr cm May 02 '22 at 11:33
2

Presented below is one possible way to achieve the desired objective.

Code Snippet

const {useState} = React;

const Thingy = ({...props}) => {
  // state variable to hold user input
  const [userInput, setUserInput] = useState('');
  
  // state variable to track user submit button click
  const [showResult, setShowResult] = useState(false);
  
  // method to update "userInput" state variable
  const handleChange = ev => (setUserInput(ev.target.value), setShowResult(false));
  
  // method to conver a single character (a to z) into number (1 to 26)
  const convertChar = ch => {
    const c = ch.toLowerCase();
    // if user input is a digit, ensure return value is a "string"
    if ('0' <= c && c <= '9') return ch.toString();
    if (!('a' <= c && c <= 'z')) return ch;         // do not convert non-alpha
    return c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
  };
  
  // method to transform user-input into numbers
  const transformInput = () => userInput
    .split('')                    // split the string into array of individual letters
    .map(c => convertChar(c))     // use the "convertChar" method
    .join(' ');                   // join back to string with "space" seperator
                        // added a "space" only for rendering to UI

  // method to find the sum/total of numbers
  const getResult = () => userInput
    .split('')                  // convert string to array of individual letters
    .map(c => convertChar(c))   // transform a-z to numbers 1-26
    .filter(                    // discard any characters except a-z, A-Z
      c => (
        typeof c !== 'string' &&    // check letter is no longer "string"
        !isNaN(c)                   // and it is not "NaN"
      )
    )
    .reduce(                    // add the numbers using ".reduce()"
      (total, itm) => total + itm, 0
    );
  
  // return the JSX that will be rendered on the UI
  // ----
  // description of elements
  // ^^^^^^^^^^^ ^^ ^^^^^^^^
  // 1. label - "enter text" to prefix the input-box
  // 2. input - to obtain the user input
  // 3. "<p>" - paragraph elt to show a-z transformed to 1-26
  // 4. button - submit button to calculate the sum
  // 5. "<p>" - paragraphe elt to show the result of the summation
  // -----
  // NOTE: Items 4, 6 and conditionally rendered
  return (
    <div>
      <div>
        <label htmlFor={'usrinp'}>Enter text: </label>
        <input
          id="usrinp"
          value={userInput}
          onChange={handleChange}
        />
      </div>
      {
        userInput.length > 0 &&
        <p>Converted text to: {transformInput()}</p>
      }
      <button onClick={() => setShowResult(true)}>
        Submit
      </button>
      {
        showResult && <p>Result is: {getResult()}</p>
      }
    </div>
  );
};

ReactDOM.render(
  <div>
    <h4>Transform User input text to numbers</h4>
    <Thingy />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

Explanation

Inline comments added to the snippet above.

jsN00b
  • 3,584
  • 2
  • 8
  • 21
  • Sir, Literally you just saved my life. i was really crying now sir. trust me words cant describe my happieness now sir. i owe you – mvsr cm May 01 '22 at 13:54
  • Sir, when i clicked "Run Code Snippet " it was working in stack overflow. but when i copied your code tried in my react js , with adding of export default in your code, the webpage showing null. – mvsr cm May 02 '22 at 10:42
  • Do you have the code in some online IDE such as codesandbox, etc? If yes, it's easy to fix. Let me know. Otherwise, please name the file as `Thingy.js` and keep only the block of code: `const Thingy = ({...props}) => { ..... all lines here ..... };` in the file. Then, use `export default Thingy` in the end (& `import React, { useState } ....` at the start). It's hard to explain it all in comments, though. – jsN00b May 02 '22 at 10:47
  • [Here](https://codesandbox.io/s/jolly-villani-nz307p) please see if this helps: [https://codesandbox.io/s/jolly-villani-nz307p](https://codesandbox.io/s/jolly-villani-nz307p) – jsN00b May 02 '22 at 10:50
  • Thank you so much for sharing your valuable link sir.. both @R4ncid sir and your code was exactly working for me . sir, last question.. what if i wanna to assign a random numbers to the alphabets. please sir, if you can please share your code sandbox link sir.. love from india – mvsr cm May 02 '22 at 11:26
  • There are various methods to map each letter to a random number. A dictionary-based approach may be better suited. `const dict = Object.fromEntries([...Array(26).keys()].map(k => ([String.fromCharCode(k+97),Math.floor(Math.random() * 100)])));` will give a dictionary; however, multiple letters may have the same number-value. It may be easier to consider an array of 26 letters and sort it randomly and then use the index of each letter as the random-value. [Check this question and its answers](https://stackoverflow.com/q/2450954/13658816). – jsN00b May 02 '22 at 11:56