首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >控制jquery验证“跳转”位置

问控制jquery验证“跳转”位置
EN

Stack Overflow用户
提问于 2011-04-16 00:04:44
回答 1查看 980关注 0票数 1

我有一张商品的桌子。每一行都有一个复选框,用于在比较视图中包含该产品。在表格的底部(在tfoot中)是一个"compare“按钮,用于提交用户的选择并向他们显示其产品的比较。

它只对用户比较2-3个产品有意义,所以我添加了jquery验证来控制这一点。为了方便起见,我将错误消息显示在与“比较”按钮相同的行中。这很有效,但有一个问题:验证插件似乎会使页面“跳”回到表单的开头,表单的开头从表格的顶部开始。这是不可取的,我宁愿只看到错误消息显示,而不发生任何其他事情。有没有一种方法可以覆盖这种跳转行为并防止它发生?

以下是该表的简化版本:

代码语言:javascript
复制
<h2 class="legend">Available Products</h2>
<form action="/products/series-comparison/" method="post" id="series-comparison-form" class="comparisonform">
<table class="product-table">
    <thead>
        <tr>
            <th>Product</th>
            <th>Models</th>
            <th>Capacities</th>
            <th class="center">Compare</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Product A</td>
            <td class="center">10</td>
            <td>From x to y</td>
            <td class="center"><input type="checkbox" class="checkbox" name="ProductSeriesId" value="465" /></td>
        </tr>
        <tr>
            <td>Product B</td>
            <td class="center">10</td>
            <td>From x to y</td>
            <td class="center"><input type="checkbox" class="checkbox" name="ProductSeriesId" value="466" /></td>
        </tr>
        <tr>
            <td>Product C</td>
            <td class="center">10</td>
            <td>From x to y</td>
            <td class="center"><input type="checkbox" class="checkbox" name="ProductSeriesId" value="467" /></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td id="compare-message-cell" colspan="3"><div id="compare-message"></div></td>
            <td class="center"><input type="submit" name="Compare" class="bttn" value="Compare" /></td>
        </tr>
    </tfoot>
</table>
</form>

以下是验证代码:

代码语言:javascript
复制
$("#series-comparison-form").validate({
    rules: {
        ProductSeriesId: {
            required: true,
            minlength: 2,
            maxlength: 3
        }
    },
    messages: {
        ProductSeriesId: {
            required: "Please select at least 2 series to compare.",
            minlength: "Please select at least 2 series to compare.",
            maxlength: "You may compare a maximum of 3 series."
        }
    },
    errorElement: "span",
    errorLabelContainer: "#compare-message"
});

如果真的不可能,那么我将把错误消息放在表格的顶部,这样用户就可以看到它。这将工作得很好,但我认为在这种情况下,跳转有点迷失方向。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-16 00:30:34

代码语言:javascript
复制
// .bttn being the button i assume you are calling validate on
$(".bttn").click(function(e){
    //prevent jump to top of page
    e.preventDefault(); 
    $("#series-comparison-form").validate({
        //your rules here
    });
});

它跳转是因为表单正在提交

尝试上面的方法或将提交按钮转换为输入按钮“type=”

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5679481

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档