2011-04-15 58 views
1

我有一個產品表。在每一行中都有一個複選框,以將產品包含在比較視圖中。在表格底部(在tfoot中)是一個「比較」按鈕,用於提交用戶的選擇並向他們顯示他們產品的比較。控制jquery驗證「跳轉」位置

它只對用戶比較2-3個產品是有意義的,所以我添加了jquery驗證來控制它。爲了方便起見,我在「比較」按鈕的同一行出現錯誤消息。這很好,但有一個問題:validate插件似乎使頁面「跳轉」回到表格的開頭,該表格從表格的頂部開始。這是不可取的,我寧願只看到錯誤信息顯示,沒有其他事情發生。有沒有辦法來覆蓋這種跳躍行爲並防止它發生?

下面是表的簡化版本:

<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> 

下面是驗證碼:

$("#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" 
}); 

如果不是真的有可能,然後我就在頂部位置錯誤消息的表,以便用戶可以看到它。這可以工作,但我認爲在這種情況下跳躍有點迷失方向。

回答

0
// .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 
    }); 
}); 

它跳躍,因爲形式提交上述

嘗試或把你的提交按鈕的輸入類型=「按鈕」

+0

感謝。這並不完全正常,但它指出了我的正確方向。我保持validate()設置在click事件之外,然後在click事件中添加if($(「#series-comparison-form」).valid()){$(「#series-comparison-form」) 。提交(); }` - 需要進行跨瀏覽器測試,但它可以在Chrome和FF中使用。 – 2011-04-15 16:58:57