2016-09-26 83 views
1

我正在開發一個網站,其中我會做一個刪除按鈕的序列,我的意思是隻有一個按鈕刪除兩個輸入字段,這是可能的做jQuery?刪除按鈕序列與jquery

這裏是我的HTML代碼:

a: <input type="text" maxlength="5" id="username" /> 
c: <input type="text" maxlength="5" id="password" /> 
<button type="button" class="delete"> 
Delete 
</button> 

這裏是我的jQuery代碼:

$("input").bind("input", function() { 
    var $this = $(this); 
    setTimeout(function() { 
    if ($this.val().length >= parseInt($this.attr("maxlength"),10)) 
     $this.next("input").focus(); 
    },0); 
}); 

$('#password').on('input', function(){ 
    if($(this).val() == ''){ 
    $('#username').focus(); 
    return false; 
    } 
}); 

$(document).on('click', '.delete', function(e){ 
         if($('#password').val == '') { 
       var $content = $('#username'); 
      } else if ($('#password').val !== '') { 
       var $content = $('#password'); 
      } 
      var html = $content.val(); 
      $content.val(html.substr(0, html.length - 1)); 
      if($content.val() == '') { 
      $('#username').focus(); 
      } else if ($content.val() !== '') { 
      $content.focus(); 
      } 
      return false; 
    }); 

JSFiddle Demo

我已經嘗試過自己,但都沒有成功!

+0

單擊「刪除」按鈕時,您想要執行什麼操作? –

+0

@PraneshRavi清除輸入字段。 –

+0

是的夥計,當「刪除」按鈕點擊@PraneshRavi –

回答

2

這個問題的關鍵是序列。所以只需檢測輸入值的長度。

$("input").bind("input", function() { 
 
    \t var $this = $(this); 
 
    setTimeout(function() { 
 
    \t if ($this.val().length >= parseInt($this.attr("maxlength"),10)) 
 
    \t $this.next("input").focus(); 
 
    },0); 
 
}); 
 
    
 
$('#password').on('input', function(){ 
 
    if($(this).val() == ''){ 
 
    $('#username').focus(); 
 
    return false; 
 
    } 
 
}); 
 

 
$(document).on('click', '.delete', function(e){ 
 
\t var username = $('#username'); 
 
    var password = $('#password'); 
 
    password.val(password.val().substr(0, password.val().length - 1)); 
 
    
 
    if (password.val().length == 0) { 
 
    \t username.val(username.val().substr(0, username.val().length - 1)); 
 
    } 
 
\t return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
a: <input type="text" maxlength="5" id="username" /> 
 
c: <input type="text" maxlength="5" id="password" /> 
 
<button type="button" class="delete"> 
 
Delete 
 
</button>

+0

是啊tq,我希望密碼第一次點擊刪除按鈕時,但是沒問題,謝謝幫助我。 –

+0

@RofiFathurrohman我改變了順序。你可以檢查它。 –

2

你忘了在Val檢查括號在你刪除功能的開始。在每個中將val更改爲val():

if($('#password').val() == '') { 
    var $content = $('#username'); 
} else if ($('#password').val() !== '') { 
    var $content = $('#password'); 
} 
+0

啊屎我的錯,謝謝你兄弟! –