apatik apatik - 3 months ago 17
CSS Question

email type input : dynamically change color/text of the button if the email is wrong or correct

I have an email type input inside a form where a user can submit his email address to recover his password if this one has been forgotten.

By default, if the user hasn't typed anything inside the input, the button simply displays a grey @ symbol.

I'm looking for a way, once the user starts typing in the input, to change the text/color of the submit button (for instance an orange "X" when the email is incorrect, and a green "check" when it's correct.

How can I achieve that ?

Answer

Try it :

<html>
    <title>This is test</title>
    <head>
        <style>
            .btn {
                color:#000;
                -webkit-transition: background 1s linear;
                -moz-transition: background 1s linear;
                -ms-transition: background 1s linear;
                -o-transition: background 1s linear;
                transition: background 1s linear;
            }
        </style>
    </head>
    <body>
        
        Enter Email : <input type="text" class="email">
        <button class="btn">Submit</button>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>

         $(document).ready(function(){
             
              $(".email").on("input",function(){
                  
                  if ($(this).val() == "")
                      $(".btn").css({backgroundColor:""});
                  
                  else {
                      if (checkEmail($(this).val()))
                          $(".btn").css({backgroundColor:"green"});
                      else
                          $(".btn").css({backgroundColor:"red"});
                  }
              })
              
              function checkEmail(txt) {
                  var patt = /[a-zA-Z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,3}$/;
                  if(patt.test(txt))
                      return true;
                  else
                      return false;
              }
         })

        </script>
    </body>
</html>

Comments