启用输入字段X的输入字段X + 1 onChange

时间:2012-12-08 02:09:56

标签: javascript jquery html

所以每个'特殊输入'div都包含一个输入字段。我正在尝试规范何时可以将每个信息输入到每个输入字段中。

最初,我希望启用顶部的第一个输入字段,同时禁用其下方的其余输入字段。

输入字段1的OnChange,我希望它下面的下一个输入字段被启用,而其余的被禁用。在输入字段2的OnChange中,我希望输入字段3变为启用状态,而其余字段仍然禁用,等等...

我知道我可以使用JQuery的attr()来在需要时启用输入字段,但我不确定如何应用逻辑来实现这一点,因为JQuery对我来说是一个新手。

<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
...... 
...... 
......
<div class="special-input"><input type="text" /></div>

2 个答案:

答案 0 :(得分:1)

    // Cache the inputs, this is a good way to improve performance of your 
    // jQuery code when re-using selectors.
        var $inputs = $('.special-input :input');
    // Disable all except the first input
        $inputs.not(':first').attr('disabled', 'disabled');
        $inputs.each(function(i) {
    // For each input, bind a change event to enable the next input, 
    // if the user presses enter, the next textbox will receive focus. if the user
    // presses tab, the following input won't receive focus, so you'll have to add 
    // code if you want this to work.
            $(this).on('change', function() {
                // Get the index of the current input element we're looking at,
                // We need to re-wrap the $input[i] element as it is now a normal 
                // DOM element.
                var $nextInput = $($inputs[i + 1]);
                $nextInput.removeAttr('disabled').focus();
            });
        });​

修改:您可以在http://jsfiddle.net/dFZEq/11/

看到一个有效的示例

编辑2:

要在满足特定条件后启用下一行的元素集,请使用:

var $specialInputs = $('.special-input');

// don't disable the first line's input elements.
$specialInputs.not(':first').find(':input').attr('disabled', 'disabled');

$specialInputs.on('change', function() {
    var $this = $(this);

    if ($this.find(':input').filter(function() {
        // you can change this filter to match any condition you 
        // like, for now we'll just make sure all inputs have a non-empty value
        return $(this).val() == '';
    }).length == 0) {

        var $nextInputSet = $($specialInputs[$this.index() + 1]).find(':input');

        // enable the next set of elements
        $nextInputSet.removeAttr('disabled');

        // focus your element here, requires more work
        $nextInputSet.first().focus();
    }
});​

http://jsfiddle.net/tFG5W/

的示例

答案 1 :(得分:0)

我没有测试过以下代码,但看起来应该是这样的:

$(".special-input").bind("change",function(event){
    $(this).attr("disabled","disabled");
    $(this).next().removeAttr("disabled").focus();
});