如何让用户必须单击按钮才能验证表单?

时间:2013-10-23 21:09:53

标签: javascript html asp.net-mvc-4 jquery-validate knockout-mvc

我有一组按钮,需要点击其中一个按钮才能进入下一个表单:

<div class="btn-group" data-toggle="buttons-radio">
                        <button type="button" class="btn" data-bind="click: sportYes">Yes</button>
                        <button type="button" class="btn" data-bind="click: sportBasic">Basic</button>
                        <button type="button" class="btn" data-bind="click: sportNo">No</button>
                    </div>

我正在使用jquery验证,我想写一个validate方法,但我不能使用我的典型方法,例如给文本字段一个必需的值,例如。

$("#FormThatNeedsToBeValidated").validate({
    rules: {
        textinput1: {
            required: true
        },
        textinput2: {
            required: true
        }}});

即使我知道语法,我也不认为这会有所帮助,因为不需要所有按钮。 有没有办法利用单击我的三个按钮之一时呈现的active属性?

1 个答案:

答案 0 :(得分:1)

<button>不符合使用此插件进行验证的条件。

此插件仅适用于以下八种数据输入元素(每个必须具有唯一的name属性),同时必须在表单元素中:

<form>

   <!-- Textbox Input - Also including the various HTML5 input types -->
   <input type="text" name="something" />

   <!-- Password Input -->
   <input type="password" name="pw" />

   <!-- Radio Button -->
   <input type="radio" name="foo" />

   <!-- Checkbox -->
   <input type="checkbox" name="bar" />

   <!-- File Upload -->
   <input type="file" name="upload" />

   <!-- Hidden Input - 'ignore: []' must be defined in the options -->
   <input type="hidden" name="hide" />

   <!-- Select Dropdown -->
   <select name="foobar"> ... </select>

   <!-- Text Area Box -->
   <textarea name="barfoo"></textarea>

</form>

另请参阅文档中的“参考”页面:http://jqueryvalidation.org/reference/


为了达到预期的效果,你可以测试&amp;单击特定按钮后提交表单。使用the .valid() method进行测试/检查,然后submit()提交表单。

<强> HTML

<button type="button" class="btn" id="sportYes">Yes</button>
<button type="button" class="btn" id="sportBasic">Basic</button>
<button type="button" class="btn" id="sportNo">No</button>

<强>的jQuery

$(document).ready(function() {

    $("#FormThatNeedsToBeValidated").validate({  // <- initialize plugin on form
        // rules & options
    });

    $('#sportYes').on('click', function() {
        // stuff to do when this button is clicked
        if ($("#FormThatNeedsToBeValidated").valid()) { // <- test validity
            // stuff to do on valid form
            $("#FormThatNeedsToBeValidated").submit();  // <- submit the valid form
        }
    });

    $('#sportBasic').on('click', function() {
        // stuff to do when this button is clicked
    });

    $('#sportNo').on('click', function() {
        // stuff to do when this button is clicked
    });

});

DEMO:http://jsfiddle.net/PgCr2/