2016-07-05 46 views
-1

我有一組相同名稱的複選框。用戶需要至少選擇一個複選框,如果選擇「其他」,則必須使用「Promotion_Others」文本框。如果選擇了特定的複選框,使文本框強制(複選框組)

我不知道如何做到這一點與所有具有相同名稱的複選框。

<input type="checkbox" name="Prefer_Promotion[]" value="food_and_beverages_discounts" >Food & beverages discounts</label> 
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_hotel_facilities">Complimentary hotel facilities</label> 
<input type="checkbox" name="Prefer_Promotion[]" value="complimentary_gym_access">Complimentary gym access</label> 
<input type="checkbox" name="Prefer_Promotion[]" value="others">Others</label> 
<input type="text" class="form-control" name="Promotion_Others" value="" maxlength="50"/> 

回答

0
<html> 
    <head> 
     <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script> 
     <script> 
      $(document).ready(function() { 
       $('#mysubmit').click(function() { 
        if ($('input[type=checkbox]').is(':checked')) { 
         // atleast one checkbox checked, do something... 
         // now check seleted is othere 

         $('input[type=checkbox]input:checkbox:checked').each(function() { 
          var value = $(this).attr('value'); 
          if ('others' === value) { 

           var others_value = $('.form-control').val(); 
           if (!others_value) { 
            alert('Please fill text field'); 
            return false; 
           } else 
            return true; 
          } 
         }); 
        } 
       }); 

      }); 

     </script> 
    </head> 
    <body> 
     <form id="myform"> 
      <input type="checkbox" name="Prefer_Promotion[]" value="food_and_beverages_discounts" >Food & beverages discounts</label> 
      <input type="checkbox" name="Prefer_Promotion[]" value="complimentary_hotel_facilities">Complimentary hotel facilities</label> 
      <input type="checkbox" name="Prefer_Promotion[]" value="complimentary_gym_access">Complimentary gym access</label> 
      <input type="checkbox" name="Prefer_Promotion[]" value="others">Others</label> 
      <input type="text" class="form-control" name="Promotion_Others" value="" maxlength="50"/> 
      <input type="button" value="submit" id="mysubmit"/> 
     </form> 
    </body> 
</html> 

試試這個片斷。評論是否需要幫助

+0

我想使用jQuery需要驗證,但我有困難與If語句的第二部分。其他:{ 要求:{ 取決於:function(element){ if(($(「input [name ='Prefer_Promotion []']:checked」)。length> 0)&&(如果複選框數組包含'others' )){ \t \t return true; \t} } } }, – Spiral1ng

+0

@ user558085這是一個完全不同的問題。請接受此問題的正確答案,然後將其作爲一個新問題提出。只要您發佈新問題,您就會立即看到數十隻眼睛並嘗試提供幫助,而不是等待現在這個問題後面的少數人迴應。 – gibberish

+0

我測試了這段代碼。它的工作原理。 @ user558085:如果這有幫助,你可以接受答案 –