Output third and fourth placement of digit from an input text in javascript with html

Viewed 60

How can i output third and fourth placement of digit from an input text in javascript with html?

For example user input 567899, i want to read the 78, and output it..

Here is my code:

function myFunction() {
    num = Number(document.getElementById('num').value);
    var one = String(num).charAt(4,5);
    document.getElementById("output").innerHTML = one;
}
<!DOCTYPE html>
<html>
    <body>
        <tr>
            <td>Number:</td>
            <td><input type="text" id="num"></td>
        </tr>
        <button onclick="myFunction()">submit</button>
        <p id="output"></p>
    </body>
</html>

3 Answers

You can use substring() to get all number from some position.i.e :

function myFunction() {
    num=Number(document.getElementById('num').value);
    var one = String(num).substring(2, 4); //getting letter at 3rd and 4th position
    document.getElementById("output").innerHTML = one;
}
<!DOCTYPE html>
<html>
    <body>
       <tr>
           <td>Number:</td>
           <td><input type="text" id="num"></td>
       </tr>
       <button onclick="myFunction()">submit</button>
       <p id="output"></p>
   </body>
</html>

You can do this with the help of for loop.


function myFunction()
{

let word=document.getElementById('num').value;
let output=null;

for(let i=0;i<word.length;i++)
{
  if(i === 2 || i === 3)
{
output+=word[i];
}


}
return output;

}

Based off the answer, is the expected value coming from the input [text] always going to be digits? Meaning, no characters, decimals, or spaces? From your original question, the accepted answer for "567899" will work.

I would advise the Number function and the String function be removed, as these will only cause NaN errors if the user inputs any value other than digits.

Additionally, the code below will not allow spaces or characters to be entered into the input text field. It would be advised to add another validation to notify the user that at least (4) digits needs to be inserted into the text input (hence, the substring for your 3rd and 4th digit would be absolute).

You should move the onkeypress function outside of the global JS functions, as this would inhibit other [literally] keys for your whole website. Was only used as an example.

<input type="text" id="num">

<button onclick="myFunction()">submit</button>

<p id="output"></p>
function myFunction() {
  var num = document.getElementById('num').value;

  if (num.length < 4) {
    return false;
  }

  var one = num.substring(2, 4); //getting letter at 3rd and 4th position
  document.getElementById("output").innerHTML = one;
}

document.getElementById('num').onkeypress = function(evt)
{
   evt = (evt) ? evt : window.event;
   var charCode = (evt.which) ? evt.which : evt.keyCode;

   if (charCode >= 32 && (charCode < 48 || charCode > 57)) {
      return false;
   }

   return true;
}

JS Fiddle - https://jsfiddle.net/5haz3qbs/

Related