使用jquery

时间:2016-09-26 02:38:12

标签: javascript 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

我自己尝试过,但没有成功!

2 个答案:

答案 0 :(得分:2)

此问题的关键是序列。所以只需检测输入值的长度。

&#13;
&#13;
$("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){
	var username = $('#username');
  var password = $('#password');
  password.val(password.val().substr(0, password.val().length - 1));
  
  if (password.val().length == 0) {
  	username.val(username.val().substr(0, username.val().length - 1));
  }
	return false;
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您在删除功能开始时忘记了val检查中的括号。在每个中将val更改为val():

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