javascript - 使用带验证的 href a long 提交表单

标签 javascript jquery

我在处理这个小脚本时遇到了问题。 我有一份产品 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>

JSFiddle

最佳答案

您应该始终尝试使您的脚本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/

相关文章:

javascript - 可排序列表重叠并防止拖放

javascript - 在动态插入的 jQuery 库完成加载后执行我的 jQuery 脚本

javascript - ASP MVC 将两个控件绑定(bind)到一个字段

javascript - 使 iframe 适合其内容高度

javascript - 从 switch 语句返回 false

关联数组对象上的 JavaScript foreach 循环

javascript - 使用 div jquery 创建 div

jquery - 使用开始标签与自结束标签创建空元素

javascript 验证文本框的数字和字符串

javascript - 如何在Vala中的webkit2gtk-4.0中获取JS结果?