Home  >  Article  >  Web Front-end  >  Javascript sends SMS verification code implementation code_javascript skills

Javascript sends SMS verification code implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:32:461877browse

This article first analyzes the principle of sending verification codes by mobile phones, and then implements javascript to send SMS verification codes. The specific ideas are as follows:
After clicking the "Send Verification Code" button, the buttons will display "Retry in 59 seconds", "Retry in 58 seconds"... until the countdown reaches 0 seconds and then return to "Send Verification Code". The button is disabled during the countdown.

The first step, get the button, bind the event, set the timer variable and timing variable

The second step is to add a timer , and the timer will decrease by 1 every 1 second until the timer is cleared when the timer is less than or equal to 0, and the button will return to "Send Verification Code" ”, otherwise it will be displayed as “Retry in X seconds”

Rendering:

Implementation code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script type="text/javascript">
  window.onload=function(){
    var send=document.getElementById('send'),
      times=60,
      timer=null;
    send.onclick=function(){
     // 计时开始
     var that = this;
      this.disabled=true;
      timer = setInterval(function(){
        times --;
        that.value = times + "秒后重试";
        if(times <= 0){
          that.disabled =false;
          that.value = "发送验证码";
          clearInterval(timer);
          times = 60;
        }
        //console.log(times);
      },1000);  
    }  
  } 
  </script>
</head>
<body>
  <input type="button" id="send" value="发送验证码">
</body>
</html>

Note:

When setting whether the button is disabled, send.disabled=true; send.disabled=false;
True and false cannot be quoted! True and false cannot be quoted! True and false cannot be quoted! Otherwise the value will always be true.
You can also use send.setAttribute('disabled','disabled');
or send.removeAttribute('disabled');

The above is all the codes for sending SMS verification codes via javascript shared with you. I hope it will be helpful to your study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn