我在处理这个小脚本时遇到了问题。 我有一份产品 list 。每个产品都可以从此列表添加到购物车。
但我需要验证是否选择了变体。 验证工作正常,但提交不行。
JS:
function submitForm() {
if ($('#variants').val() !== '') {
$(this).closest('form').submit();
} else {
alert("You need to pick variant");
}
}
HTML:
<form id="form" action="FormPost.aspx">
<select name="variants" id="variants" class="variants">
<option value="">Select variant</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Red">Red</option>
</select>
<a href="javascript:submitForm();" class="addToCart buybtn_small text-left pull-right">Buy</a>
</form>
最佳答案
您应该始终尝试使您的脚本unobtrusive 。
使用 jQuery 的 .click()
方法替代:
$('.addToCart').click(function(e){
e.preventDefault();
var form = $(this).closest('form');
// to access the select by tag name:
if (form.find('select').val()) {
// to access the select by class:
// if (form.find('.variants').val()) {
form.submit();
} else {
alert("You need to pick variant");
}
});
HTML:
<form id="form" action="FormPost.aspx">
<select name="variants" id="variants" class="variants">
<option value="">Select variant</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Red">Red</option>
</select>
<a href="#" class="addToCart buybtn_small text-left pull-right">Buy</a>
</form>
关于javascript - 使用带验证的 href a long 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31969443/