如果两个单选按钮设置为"Yes",如何组合它们以显示相同的元素?



这是我在jQuery中所拥有的:

$(document).ready(function(){
    $("input[name='DifficultyObtainingCMELicenseRenewal']").change(function() {
      $("#DifficultyObtainingCME").toggle(this.value == "Yes");
    });
    $("input[name='DifficultyObtainingCMEBoardCertification']").change(function() {
      $("#DifficultyObtainingCME").toggle(this.value == "Yes");
    });
});

这是 HTML:

 <tr>
    <th><label>Do you have difficulty obtaining enough CME required for Iowa license renewal?</label></th>
    <td>
        <label><input type="radio" name="DifficultyObtainingCMELicenseRenewal" value="Yes" class="checkbox"/> Yes</label><br />
        <label><input type="radio" name="DifficultyObtainingCMELicenseRenewal" value="No" class="checkbox"/> No</label>
    </td>
  </tr>
  <tr>
    <th><label>Do you have difficulty obtaining enough CME required for your specialty board certification/re-certification?</label></th>
    <td>
        <label><input type="radio" name="DifficultyObtainingCMEBoardCertification" value="Yes" class="checkbox"/> Yes</label><br />
        <label><input type="radio" name="DifficultyObtainingCMEBoardCertification" value="No" class="checkbox"/> No</label>
    </td>
  </tr>
  <tr id="DifficultyObtainingCME" style="display:none">
    <th class="altTH"><label>Please elaborate on the difficulties you are experiencing:</label></th>
    <td class="altTD">
        <cftextarea name="DifficultyObtainingCMEOther" rows="3" cols="20"></cftextarea>
    </td>
  </tr>

因此,现在如果您在其中一个框上按"是",它会显示额外的字段,但是在另一个框中按"否"会使其消失,反之亦然。我该怎么做,只要其中任何一个设置为"是",它就会保持打开状态?

这是一个链接:http://jsfiddle.net/madcaesar/hcZXf/

只需确保在更改发生时选中"是"选项:

var thingToToggle = $("#DifficultyObtainingCME");
var allRadios = $('input[type="radio"]');
allRadios.change(function () {
    if (allRadios.filter(function () {
        return this.checked && this.value === 'Yes';
    }).length > 0) {
        thingToToggle.show();
    } else {
        thingToToggle.hide();
    } 
});

http://jsfiddle.net/JptF8/

$('input[type="radio"]').change(function() {
if ($('input[type="radio"][value="Yes"]:checked').length > 0) {
    $("#DifficultyObtainingCME").show();
} else {
    $("#DifficultyObtainingCME").hide();
}
});

当然,如果您稍后添加更多单选按钮,这也将适用于这些按钮。在这种情况下,将一个类添加到您希望应用它的类中(例如 $('.toggleRadioClass[value="Yes"]:checked'))。不确定 $("#DifficultyObtainingCME").toggle(this.value == "Yes");应该这样做,但我的代码实际上会显示和隐藏元素。

基于:checked yes-radios的存在来显示可见性:

var $radios = $("input[name^='DifficultyObtainingCME']"),
    $toggle = $("#DifficultyObtainingCME");
$radios.on("change", function(){
    $toggle.toggle(!!$radios.filter("[value='Yes']:checked").length);
});

小提琴:http://jsfiddle.net/8wD8D/3/

最新更新