|
一般信用卡的UI會用4格Input Text來呈現,要達到填寫信用卡或序號時,只要填滿就會自動跳下一欄位,我們要借助Javascript才有辦法達到此效果。
範例一:此範例使用原生JS,轉貼自用Javascript達到信用卡或序號填寫時自動跳下欄位的方法
首頁我們在html 先把要輸入的欄位列出:- 信用卡卡號
- <input type=text name=pan_no1 size=4 value="" maxlength=4 onKeyUp="setBlur(this,'pan_no2');">-
- <input type=text name=pan_no2 size=4 value="" maxlength=4 onKeyUp="setBlur(this,'pan_no3');">-
- <input type=text name=pan_no3 size=4 value="" maxlength=4 onKeyUp="setBlur(this,'pan_no4');">-
- <input type=text name=pan_no4 size=4 value="" maxlength=4 >
複製代碼 再來寫個 Javascript,判斷該欄位填入的長度是不是等於maxLength如果是就跳下一個欄位- <script>
- function setBlur(obj,target2)
- {
- var target =document.getElementById(target2);
- if( obj.value.length ==obj.getAttribute('maxlength'))
- {
- target.focus();
- }
- return;
- }
- </script>
複製代碼
範例二:使用JQuery,包含判定輸入為數字:
- // 信用卡卡號自動跳下欄位
- $('body').find('#coupon-focus').children('input').focus().select();
- $('body').find('#coupon-focus').children('input').keyup( function(e){
- // 限制只能輸入數字
- if(!/^\d+$/.test(this.value)){
- var newValue = /^\d+/.exec(this.value);
- newValue != null ? $(this).val(newValue) : $(this).val('');
- }
- this.value.length == this.getAttribute('maxlength') && $(this).next().focus();
- });
複製代碼 此範例就不多做解釋,自己修改選擇器以達到需求。 |
|