2

私は次のようなフォームマークアップを持っています...

<form id='cart' action="/cart/add" method="post">
    <div id="product-variants">
        <div class="selector-wrapper clearfix">
        <select class="product-select" name='id[]'>
            <option value="">&nbsp;---</option>
            <option value="a">Option A</option>
            <option value="b">Option B</option>
            <option value="c">Option C</option>
        </select>
        <select class="product-select" name='id[]'>
            <option value="">&nbsp;---</option>
            <option value="a">Option A</option>
            <option value="b">Option B</option>
            <option value="c">Option C</option>
        </select>
        </div>
    </div>
</form>

値が空白である選択入力をフィルターで除外(無効化)して、制御できないバックエンドに送信されないようにするルーチンを作成しようとしています。ここで見つけた他の質問への回答に基づいて私が思いついたものは次のとおりです。

jQuery(function(){
  jQuery("#cart").submit(function(){
    $(this).children(':input[value=""]').attr("disabled", "disabled");
    $(this).children('select option[value=""]').parent().attr("disabled","disabled");
    return true; // ensure form still submits
  });
});

ただし、送信機能の2行目は機能していません。私はいくつかの組み合わせを試しましたが、これを達成する方法がわかりません。誰かが私が間違っていることについて私に教えてもらえますか?

4

2 に答える 2

4

これを試すことができます

$(this).find('select').filter(function() {
      return this.value === ''
 }).prop("disabled", true);

また

$(this).find('select').each(function() {
     if (this.value == '') {
        $(this).prop("disabled", true);
     }
});

完全なコード

jQuery(function() {
    jQuery("#cart").submit(function(e) {
       // e.preventDefault();
        $(this).find('select').each(function() {
            if (this.value == '') {
                $(this).prop("disabled", true);
            }
        });
    });

    jQuery("#cart").submit();
});​

フィドルをチェック

もうひとつ

于 2012-10-31T00:44:35.437 に答える
0
jQuery("#cart").submit(function(e) {
  jQuery(this).find(':input').prop('disabled',function(){/* ':input will find select and input tags*/
        return $(this).val() =='';
   });
});

送信ハンドラーで true を返すことは冗長です。初期コードのもう 1 つの問題はselectinput要素がフォームの子ではないことです。children直系の子孫です

于 2012-10-31T00:54:35.783 に答える