单选按钮的onclick显示/隐藏内容

时间:2018-08-14 02:25:50

标签: javascript html jsp

现在,我在jsp页面中具有一项功能:选择是单选按钮并保存表单时,它会显示span(此功能运行良好)。

<s:if test="%{test ==Y}" > 
    //displaying span

但是现在,当人们尝试更新表单时,我有了新的要求,如果他们没有选择单选按钮,则跨度应该消失,反之亦然。我尝试使用JS,但未触发任何事件。请帮助我,当他们单击“是/否”单选按钮

时,我必须隐藏/显示跨度

function bet() {
    var test_1 = document.getElementsByName('test');
    if (test_1[0].checked) {
        document.getElementById('testing').style.visibility = "visible";
    }
    if (!test_1[0].checked) {
        document.getElementById('testing').style.visibility = "hidden";
    }
}
Yes<input type="radio" name="test" title="yes" onClick="bet()" value="Y">
No<input type="radio" name="test" title="NO" onClick="bet()" value="N">

<span id="testing">This is a test</span>

2 个答案:

答案 0 :(得分:2)

尝试一下

document.addEventListener('DOMContentLoaded', function(){
  // get radio options
  var options = document.getElementsByName('test'),
      // ref content
      content = document.getElementById('testing'),
      // ref content display prop
      originalDisplayStyle = content.style.display;

  options.forEach(function(option){
    // listen for onclick event
    option.addEventListener('click', function(){
      var display = this.value === 'N' && this.checked ? 'none' : originalDisplayStyle;
      // hide/show content based on selection
      content.style.display = display;
    });
  });
});
Yes<input type="radio" name="test" title="yes" value="Y">
No<input type="radio" name="test" title="NO" value="N">


<span id="testing">This is a test</span>

答案 1 :(得分:0)

您必须将 onclick 与单选元素绑定。

var radioBtn = document.getElementsByName('test');

for (var i = 0, len = radioBtn.length; i < len; i++) {
  radioBtn[i].onclick = function() {

    if (this.value === 'Y') {
      document.getElementById('testing').style.visibility = "visible";    
    } else {
      document.getElementById('testing').style.visibility = "hidden";
    }

  }
}