2

我想要做的是,当用户登陆表单时。我希望第一个输入处于活动状态,以便用户能够单击、选择或填写它。我希望他们一步一步地填写表格,所以我希望下一个输入只有在他们填写完当前输入后才能激活。

我还希望禁用提交按钮,并且在填写所有输入之前不要激活。

实现这一目标的最佳方法是什么?

我附上了一张图片来说明我正在尝试做的事情。

在此处输入图像描述

4

2 回答 2

4

这可能会给你一个很好的起点:小提琴

为您的每个表单元素添加一个step类(我相信要使其正常工作,它们需要成为彼此的兄弟姐妹):

<form class="step-by-step">
    <!-- Start with only the first one enabled -->
    <input type="text" class="step" id="step1" />
    <input type="text" class="step" id="step2" disabled />
    <input type="text" class="step" id="step3" disabled />
    <!-- Also works with selects,
         as long as you keep track of IDs -->
    <select id="step4" class="step" disabled>
        <option value="">Choose one</option>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
    <select id="step5" class="step" disabled>
        <option value="">Choose one</option>
        <option value="europe">Europe</option>
        <option value="america">America</option>
    </select>
</form>

然后,使用该next()函数在某些更改时查找表单中的下一步,并禁用或启用它(或所有后续步骤,如果元素为空):

// The change event is fired when a form element loses focus
// and its value has changed since the last time we interacted with it
$('.step').change(function() {
    var next_step = $(this).next('.step');
    var all_next_steps = $(this).nextAll('.step');
    // If the element *has* a value
    if ($(this).val()) {
        // Should also perform validation here
        next_step.attr('disabled', false);
    }
    // If the element doesn't have a value
    else {
        // Clear the value of all next steps and disable
        all_next_steps.val('');
        all_next_steps.attr('disabled', true);
    }
});

对于 TAB 功能,以下是一个快速修复,我确信它可以以某种方式与上述功能集成。

$('.step').keydown(function(event) {
    // If they pressed tab AND the input has a (valid) value
    if ($(this).val() && event.keyCode == 9) {
        $(this).next('.step').attr('disabled', false);
    }
});
于 2013-07-30T17:06:14.807 回答
0

有几点需要考虑:

可以通过单击带有 type="submit" 的按钮或返回键来提交表单。

所以,为了让你达到想要的效果:

  1. $("form").find("input:first").focus(); // 自动聚焦第一个输入字段。
  2. 确保所有输入都具有“tabindex”属性,以便用户可以循环使用选项卡。
  3. Javascript 必须禁用表单操作,直到用户通过验证。
于 2013-07-30T16:17:39.027 回答