我有一个表单,我使用jquery来检测按钮何时被按下,以及用于在没有页面重新加载的情况下显示数据。
按下按钮时工作正常,但按下输入时页面刷新,没有任何反应。我有按钮绑定到jquery,但我不知道如何处理按Enter键。
HTML:
<table border="0" width="100%" cellspacing="1" cellpadding="2" style="margin-bottom:20px;">
<tbody>
<tr class="infoBoxContents">
<td style="padding:20px;">
<table border="0" width="100%" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="50%">
<table width="100%">
<tbody>
<tr>
<td class="main">
<b>Calculate shipping</b>
<div class="smallText">Shipping Weight: 6lbs</div>
</td>
</tr>
<tr>
<td class="main" style="padding:10px;">Country:
<select name="ship_country_id" id="ship_country_id">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<br>Post code/ Zip code:
<input type="text" name="postcode" id="postcode_entry">
</td>
</tr>
</tbody>
</table>
</td>
<td class="main" width="50%" align="right">
<div class="contentText" id="shipping_method"></div>
</td>
</tr>
<tr>
<td>
<button type="button" id="estimate" style="cursor:pointer; width:110px; margin-left:10px; padding:5px;">
<span class="ui-button-text" style="float:left;">Calculate</span>
<span class="ui-button-icon-secondary ui-icon ui-icon-triangle-1-e" style="float:right;"></span>
</button>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
的javascript:
$(function () {
$('#estimate').click(function () {
var postcode_entry = $('#postcode_entry').val();
var country_entry = $('#ship_country_id').val();
$("#shipping_method").html("<div style=\'margin:20px auto;width:100px;text-align:center;\'><img src=\'ext/jquery/bxGallery/spinner.gif\' /></div>").show();
$.get("checkout_shipping.php", {
country: country_entry,
refresh_quotes: "1",
postcode: postcode_entry,
zone_name: "canada"
},
function (data) {
$("#shipping_method").html(data);
}
);
});
});
答案 0 :(得分:3)
单击按钮时,不要运行代码,而是在提交表单时运行代码。
$('YOUR_FORM_HERE').submit(function() {
这将抓住提交表格的任何方式。
答案 1 :(得分:3)
那是因为你需要找到submit
上发生的事情 - 这是按Enter键时调用的事件,它不会触发按钮的点击。
我不知道您form
的ID是什么,但您可以执行以下操作:
$("#myform").submit(function(e) {
e.preventDefault();
//do something
...
使用此代替按钮点击事件。
答案 2 :(得分:0)
您可以添加此jQuery以绑定到同一事件:
$(document).on('keypress', function(e){
if(e.which === 13){
$('#estimate').click();
}
});
虽然最好将执行的函数分离到一个单独的函数中,然后调用它,这仍然可以正常工作。