Faking numeric input with individual inputs.

In this example below you will see how to do a Faking numeric input with individual inputs. with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by magnus16, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright magnus16 ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Faking numeric input with individual inputs.</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="box">
  <div class="inpt"></div>
  <div class="inpt"></div>
  <div class="inpt"></div>
  <div class="inpt"></div>
  <div class="inpt"></div>
  <div class="inpt"></div>
</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/magnus16/faking-numeric-input-with-individual-inputs-WpwKWY */
html,body{
  background:#222;
}
.box{
  background:#444;
  position:absolute;
  left:50%;
  top:50%;
  width:370px;
  height:70px;
  display:flex;
  justify-content:space-between;
  padding-left:10px;
  padding-right:10px;
  align-items: center;
  transform:translateX(-50%) translateY(-50%);
}
.inpt{
  background:#fff;
  height:50px;
  width:50px;
  font-family:sans-serif;
  font-weight:bold;
  color:#222;
  font-size:40px;
  line-height:50px;
  text-align:center;
}
.box.focus .inpt{
  background:#fff;
}

/*Downloaded from https://www.codeseek.co/magnus16/faking-numeric-input-with-individual-inputs-WpwKWY */
$('.box').on('click', function(e) {
  e.stopPropagation();
  $(this).addClass('focus');
});
$('html').on('click', function() {
  $('.box').removeClass('focus');
});

$('body').on('keydown', function(e) {
  var flag;
  if (e.keyCode == 8) {
    var lastInputWithText;
    $.each(Array.from($('.inpt')).reverse(), function(i, v) {
      if ($(v).text() != "") {
        lastInputWithText = $(v);
        return false;
      }
    });
    lastInputWithText.text("");
    return false;
  } 
  else if(e.keyCode==13){
   var text = Array.from($('.inpt')).map(function(v){
     return $(v).text();
   }).join("");
    alert(text);
    return false;
  }
  else if (e.keyCode < 48 || e.keyCode > 57) {
    return false;
  }
  var firstInputWOText;
   $.each($('.inpt'), function(i, v) {
      if ($(v).text() === "") {
        firstInputWOText = $(v);
        return false;
      }
    });
  firstInputWOText.text(String.fromCharCode(e.keyCode));
  //console.log(String.fromCharCode(e.keyCode));
});

Comments