如果选择了单选按钮,则显示字段

时间:2012-09-05 22:28:09

标签: javascript css

我正在尝试在this page上获取网站网址字段,以便仅在上一个问题选中单选按钮“是”时显示。我搜索并尝试了一些代码示例,但它们无法正常工作。有人对我有什么建议吗?

提前致谢!

<div class="editfield">
<div class="radio">
    <span class="label">Do you have your own website? (required)</span>
    <div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div>
</div>
</div>

<div class="editfield">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>

4 个答案:

答案 0 :(得分:2)

我注意到你最初把我给你的javascript放在页面顶部。如果要执行此操作,则需要将代码封装在jquery $(document).ready(function(){ });中。当你的html跟在javascript后面时,你只需要准备一份文件。

$(function() {
    // place code here
});

但是,在这种情况下,我创建了另一种更好的选择,但不要忘记你必须首先将web url div设置为隐藏。另外,我强烈建议您设置更好的控件ID;它会让你的javascript更容易理解。

$('input[name=field_8]').on("click",  function(){
    var $div_WebUrl = $('#field_19').closest('.editfield');

    if($('input[name=field_8]').index(this) == 0)
        $div_WebUrl.show();
    else
        $div_WebUrl.hide();
});​

Live DEMO

答案 1 :(得分:1)

我创建了一个小例子:

<div class="editfield">
<div class="radio">
    <span class="label">Do you have your own website? (required)</span>
    <div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div>
</div>
</div>

<div class="editfield" id="divUrl" style="display:none">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>​

jsFiddle:http://jsfiddle.net/EQkzE/

注意:我已经更新了div以包含样式,因为我不知道你的css类是什么样的。祝你好运。

答案 2 :(得分:0)

这是一个纯粹的JS解决方案:

document.getElementById("field_19").parentNode.style.display = "none";
document.getElementById("option_9").onclick = toggleURLInput;
document.getElementById("option_10").onclick = toggleURLInput;

function toggleURLInput(){
    document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none";
}

不是一个非常动态的解决方案,而是it works

答案 3 :(得分:0)

这样的事情会将click事件绑定到一个简单的函数,以查看单选按钮并显示另一个div。

$('#option_9').on('click', function() { 
  if ($('#option_9').is(':checked')) { 
    $('#field_19').closest('.editfield').show();
  } else {
    $('#field_19').closest('.editfield').hide();
  }
});

Run sample code

相关问题