2017-09-26 119 views
0

我有以下的HTML代碼需要單選按鈕,HTML和JavaScript

<input type="radio" name="months" value="TBI-6"> 
<input type="radio" name="months" value="UNI-6"> 

,我有這個submitt按鈕

$('#button-confirm').on('click', function() { 
    $.ajax({ 
    type: 'post', 
    url: 'index.php?route=payment/zero_rate/confirm', 
    cache: false, 
     data:{ 
     egn: $('#input-payment-egn').val(), 
     months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val() 
     }, 
    beforeSend: function() { 
     $('#button-confirm').button('loading'); 
    }, 
    complete: function() { 
     $('#button-confirm').button('reset'); 
    }, 
    success: function() { 
     location = '<?php echo $continue; ?>'; 
    } 
    }); 
}); 

我怎樣才能驗證此兩個單選按鈕?我不想讓用戶提交表單並離開頁面而不選擇單選按鈕之一?

+1

瞭解'單選按鈕的preventDefault()'函數https://api.jquery.com/event.preventdefault/ – Grasper

回答

0
$('input[name=months]:checked').length 

應該告訴你如何組在許多單選按鈕被檢查
因此,在您繼續進行表單提交之前,請驗證它是否高於0

0

檢查檢查

<input type="radio" name="months" value="TBI-6" class="radiobtn"> 
<button id="button-confirm"> 
Submit 
</button> 

$('#button-confirm').on('click', function() { 
 

 
if($('.radiobtn').is(':checked')) { alert("it's checked"); 
 

 

 
    $.ajax({ 
 
    type: 'post', 
 
    url: 'index.php?route=payment/zero_rate/confirm', 
 
    cache: false, 
 
     data:{ 
 
     egn: $('#input-payment-egn').val(), 
 
     months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val() 
 
     }, 
 
    beforeSend: function() { 
 
     $('#button-confirm').button('loading'); 
 
    }, 
 
    complete: function() { 
 
     $('#button-confirm').button('reset'); 
 
    }, 
 
    success: function() { 
 
     location = '<?php echo $continue; ?>'; 
 
    } 
 
    }); 
 
} else { 
 
     alert("it's not checked"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="radio" name="months" value="TBI-6" class="radiobtn"> 
 
<button id="button-confirm"> 
 
Submit 
 
</button>

+0

是的,但在我看到提醒後,點擊確定,頁面繼續'location ='<?php echo $ continue; '>';' –

+0

@ДобромирМилчев,在if語句內移動ajax。我更新了代碼 – Grasper

+0

現在它凍結在這個函數'beforeSend:function(){('#button-confirm')。button('loading');' –