2013-06-30 101 views
2

好吧,我環顧了其他論壇,看不到我的原因還在...... GAH。 我調用preventDefault(),所以表單不提交。我已經嘗試將動作設置爲無,然後甚至不提供表單標記上的動作屬性。Jquery preventDefault表單無法正常工作

我也嘗試做提交按鈕作爲一個按鈕,而不是提交,但它似乎並不想工作。當我不想要它時,表單仍然在提交頁面時加載頁面。我試圖用AJAX更新usershop中某個商品的價格,以便在不重新加載span標籤中的頁面的情況下更新價格的價值。

HTML:

<form id="price_form" method="POST" action="http://alkharia.localhost/user/shop/priceitem/3" accept-charset="UTF-8"><input type="hidden" name="csrf_token" value="P0oW2VxJ6HTg79ksIYl6U3R5QKapeFGwkkUKiNlQ"> 
<div class="row clearfix"> 
    <div class="full"> 
     <label for="price">Price</label> 
     <input maxlength="6" type="text" name="price" value="0" id="price"> </div> 
</div> 
<div class="row"> 
    <div class="full"> 
     <input type="hidden" name="item_id" value="3"> 
     <input type="submit" value="Submit"> </div> 
</div> 

</form> 

JQuery的:

$('#price_form').submit(function(e) { 
    e.preventDefault(); 
    var price = $('#price').val(); 
    if((Math.floor(price) == price) && ($.isNumeric(price)) && (price.length <= 6)) { 
     var itemID = $('#item_id').val(); 

     $.ajax({ 
     type: 'POST', 
     url: 'http://'+urlBase+'/user/shop/priceit/'+itemID+'/'+price, 
     success: function(msg) { 
      $('#cur_price_'+itemID).html(msg); 
     } 
    }); 
    } else { 
    alert('You can only enter an integer that is less than 999,999!'); 
    return false; 
    } 
}); 
+1

檢查你的JS控制檯是否有錯誤。你的代碼應該工作。 – Blender

+0

http://stackoverflow.com/questions/6462143/prevent-default-on-form-submit-jquery和代理:http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false –

+0

我認爲它可以工作,但它只是導致由AJAX提供的url或form action屬性。所以它提交後,而不是所有其他的邏輯加載到該頁面..:/ – Peanut

回答

0

我會完全消除e.preventDefault()和移動return false;到if/else語句之外。

如果您的條件得到滿足,則會進行AJAX調用。如果不是,則顯示警報。無論哪種方式,表單都沒有提交。

編輯後的版本:

$('#price_form').submit(function(e) { 
    var price = $('#price').val(); 

    if((Math.floor(price) == price) && ($.isNumeric(price)) && (price.length <= 6)) { 
     var itemID = $('#item_id').val(); 

     $.ajax({ 
      type: 'POST', 
      url: 'http://'+urlBase+'/user/shop/priceit/'+itemID+'/'+price, 
      success: function(msg) { $('#cur_price_'+itemID).html(msg); } 
     }); 
    } else { 
     alert('You can only enter an integer that is less than 999,999!'); 
    } 

    return false; 
}); 
-1

與錨標記替換您的 '提交' 的輸入,將href設置爲#和你的Ajax功能綁定了這一點。

+0

OP是做正確的方式。 – Blender

+0

@Blender定義「正確」......因爲如果他提交表單,然後立即試圖壓制帖子以便在頁面上做其他事情......這聽起來對我來說並不是一種表單提交。 – relic

+1

當JS被禁用時,「正確」的方式保留了可用性。如果您阻止發生'submit'事件,則表單從不提交。 – Blender

-1

將事件綁定到輸入[type = submit]點擊事件而不是表單提交。

1

好好像沒有被莫名其妙地包含在腳本文件..即使它顯示了..但我不知道,因爲我使用的JavaScript對話框,我不得不在對話框的底部再次包含該腳本。但是當我這樣做的時候,它解決了所有問題......看起來很奇怪。但是,自從返回false或比e.preventDefault()更好的選擇以來,我仍然標記了另一個正確的問題。