jQuery验证仅附加到第一个表单

时间:2012-07-25 20:44:15

标签: jquery forms validation select

我有问题验证用户是否提交默认选择选项 这是一个示例表单:

    <form action="/shopping-cart" method="post" class="eshop addtocart"   id="eshopprod7751562209795">
    <fieldset>
    <span class="eshop eselect"><label for="exopt1001562209795">Choose Size and Type…  </label><br>
    <select class="cartselectclass" id="exopt1001562209795" name="optset[0][id]"><option value="" selected="selected">Choose Option...</option>
    <option value="129">8" x 10" – Print + $9.95</option>
    <option value="130">11" x 14" – Print + $19.95</option>
    <option value="131">16" x 20" – Canvas + $299.00</option>
    </select>
   </span>
  <label for="qty7751562209795" class="qty"><abbr title="Quantity">Qty</abbr>:</label>
  <input type="text" value="1" id="qty7751562209795" maxlength="3" size="3" name="qty"   class="iqty">
   <input class="button mybutton" value="Add to Cart" title="Add selected item to your shopping basket" type="submit">
   </fieldset>
   </form>

以下是用于验证select选项的jquery: 我正在尝试的是,如果用户意外点击添加到购物车,如果他们没有选择任何选项默认选择“选择选项”,他们将获得警报。

    jQuery(document).ready(function($){

    $('select.cartselectclass option:first-child').remove();

    $('.cartselectclass').prepend('<option value="" selected="selected">Choose Option...</option>').val('');
    $('.mybutton').click(function(){

        if ($('.cartselectclass').val()=='')
        {           
                        alert('Please choose at least one option.');
            return false;
        }

    })

    $('.addtocart').submit(function(){

        var Id =$(this).attr("id");
        var data = {action: 'eshop_special_action',post:$('#'+Id).serialize() };
        $.post(""+eshopCartParams.adminajax, data,
            function(response){

            $('#'+Id +" .eshopajax").insertAfter(this).fadeIn(100).html(response).fadeOut(3000);
            setTimeout (cleareshopCart,1000);
            setTimeout (doeshopRequest,750);
            setTimeout (cleareshopRequest,3000);
        });

        function doeshopRequest(){
            var tdata = {action: 'eshop_cart'};
            $.post(""+eshopCartParams.adminajax, tdata,
            function(response){
                $(".ajaxcart").insertAfter(this).fadeOut(50).html(response).fadeIn(700);
            });
        }
        function cleareshopRequest(){
            $(".eshopajax").empty();
        }
        function cleareshopCart(){
            $(".ajaxcart").insertAfter();
        }
        return false;


    });

});

1 个答案:

答案 0 :(得分:0)

您需要修改选择器以获取正确的元素。

var Id =$(this).attr("id"); var formId = $('#'+Id).closest('form').attr("id"); 
var selval = $('#'+formId).find('.cartselectclass').attr("id"); if ($('#'+selval).val()=='') {     
alert('Please choose at least one option.'); return false; }