我正在使用 Gravity Forms 和測驗附加組件來構建調查。每個問題應該只有一個被接受的答案。但所有的答案都應該是“正確的”。
測驗附加組件的作業方式不同。它只允許單選按鈕的一個正確答案。我不能將復選框限制為只有一個答案。
所以我想我必須使用自定義 JavaScript 來允許每個欄位集只允許一個答案或復選框。
問題的欄位集如下所示:
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div >
<div id="input_3_1">
<div >
<input name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div >
<input name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div >
<input name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
目前尚不清楚最后有多少欄位集/問題。所以我需要一個靈活的解決方案。
我在這里找到了一些 JS 代碼:
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i ) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
但我不確定如何根據我的用例調整它
uj5u.com熱心網友回復:
此腳本將使每個欄位集的每個復選框互斥。
jQuery(function($) {
$('fieldset input[type="checkbox"]').on('change', function() {
// Set the checkbox just checked.
let just_checked = $(this);
// Get all of the checkboxes in the fieldset.
let all_checkboxes = just_checked.closest('fieldset').find('input[type="checkbox"]');
$.each(all_checkboxes, function(i, v) { // Loop through each of the checkboxes.
if (just_checked.prop('id') === $(v).prop('id')) {
// Check the one just checked.
$(v).prop('checked', true);
} else {
// Uncheck the others.
$(v).prop('checked', false);
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
另一種解決方案可能是使用單選按鈕,并使用 css 使它們看起來像復選框。但是 UX 說復選框不應該用作單選按鈕,反之亦然。不管那是值得的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363789.html
