如果当前选项卡具有空字段,则阻止下一个选项卡

时间:2015-06-04 18:11:17

标签: javascript jquery html

我有一个设置了很少问题的表单,每个表单一次显示(如幻灯片)。如果当前集合具有空字段,我想阻止下一组。以下是我在每个问题集中导航的脚本。任何帮助将受到高度赞赏。

$(document).ready(function() {

var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();

$('#next').click(function() {
    $($questions[currentQuestion]).slideUp(function() {
        currentQuestion++;
        if (currentQuestion == $questions.length - 1) {
            $('#next').css('display', 'none');
            $('#submit').css('display', 'inline');
        }else{
            $('#next').css('display', 'inline');
            $('#submit').css('display', 'none');
        }
        $('#back').css('display', 'inline');
        $($questions[currentQuestion]).slideDown();
    });
}); 

$('#back').click(function() {
    $($questions[currentQuestion]).slideUp(function() {
        currentQuestion--;
        if (currentQuestion == 0) {
            $('#back').css('display', 'none');
        } else {
            $('#back').css('display', 'inline');
        }
        $('#next').css('display', 'inline');
        $('#submit').css('display', 'none');
        $($questions[currentQuestion]).slideDown();
    });
});

});

这是我的JSFiddle

2 个答案:

答案 0 :(得分:1)

我遇到了你的问题并决定分叉你的小提琴。

在继续下一个标签之前,您应该创建一个检查条件的功能 在您的情况下,条件是:必须填写所有字段

我已添加此功能,检查活动部分并返回true / false,以便继续。

function validateFormSection() {
    var valid = true; //As long as it's true, we may continue
    var section = $('.question.active'); //Find the active section
    var inputs = section.find('input'); //Get all its inputs
    inputs.each(function(index, el) {
        if ( $(el).val() == "" ) {
            valid = false;
        }
    });
    return valid;
}

JSFiddle here

在第三页上,表单将提交所有字段是否为空 您可以通过挂钩提交功能并检查空字段来防止这种情况发生 如果它们被清空,我们会使用e.preventDefault();来阻止它提交 如果他们已经填写,我们只需提交$('form').submit();

即可
$('form').submit( function (e) { //Hook into the submit event
    var valid = validateFormSection(); //Check if our fields are filled
    if ( valid ) { //They are filled?
        $('form').submit(); //Very well, let's submit!
    } else {
        e.preventDefault(); //If not, prevent the (default) submit behaviour
    }
});

小提琴已被编辑以反映这些变化。

答案 1 :(得分:0)

您可以使用if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length)检查是否有空字段。小提琴:http://jsfiddle.net/ilpo/cuqerfxr/1/

  • $('.question')选择所有问题
  • .eq(currentQuestion)选择您当前所在的问题
  • .find('input')选择当前问题中的所有输入字段
  • .filter(function(){return this.value==""})仅选择空输入字段
  • .length计算匹配数量,例如空输入量
  • if(number)以正值返回true,例如如果有任何空的输入
  • 所有前面的
  • !都会反转它,如果没有空字段则返回true
相关问题