Search code examples
javascripthtmlonchangeonkeyup

How To Use on change event. Instead of onkeyup


I understand that we live in a mobile-focused world now and onkeyup is not exactly friendly to most mobile browsers' specs so I am trying to remove the attribute below from my html;

<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

And bind to the on-change event using

$('#mobile').change(function(){ check(); });

But I have no idea how to implement this on my JavaScript.

See my code sample below;

function check()
{

    var mobile = document.getElementById('mobile');
   
    
    var message = document.getElementById('message');

   var goodColor = "#03b800";
    var badColor = "#f00a0a "; 
  
    if (mobile.value.length === 11){
       
        mobile.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Good job! You entered it correctly"
   }
   else {
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
   }}
<input name="mobile"  maxlength="11" id="mobile" type="text" required onkeyup="check(); return false;" ><br/><span id="message"></span>


Solution

  • As the Comments already pointed out, you can use the onInputEvent (Inline HTML: oninput=""), which fires if the Input changes. Although onChange (Inline HTML: onchange="") does the same, it only fires if the Focus leaves the input element, which might be too late.

    // Alternativly you could add an Eventlistener if the DOMContent is fully loaded. It is practically the same.
    
    //document.addEventListener('DOMContentLoaded', function(){
    //  document.getElementById('mobile').addEventListener('input', check);
    //})
    
    function check()
    {
    
        var mobile = document.getElementById('mobile');
       
        
        var message = document.getElementById('message');
    
       var goodColor = "#03b800";
        var badColor = "#f00a0a "; 
      
        if (mobile.value.length === 11){
           
            mobile.style.backgroundColor = goodColor;
            message.style.color = goodColor;
            message.innerHTML = "Good job! You entered it correctly"
       }
       else {
            mobile.style.backgroundColor = badColor;
            message.style.color = badColor;
            message.innerHTML = "required 10 digits, match requested format!"
       }}
    <input name="mobile"  maxlength="11" id="mobile" type="text" required oninput="check()"><br/><span id="message"></span>