0

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

    <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>

这是用于验证选择选项的 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;


    });

});
4

1 回答 1

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; }
于 2014-09-07T05:34:12.337 回答