简体   繁体   English

单击单选按钮时如何激活下拉列表

[英]How to activate a dropdown list when I click a radio button

I have the following radio buttons and a dropdown in my rails form. 我有以下单选按钮和rails表单中的下拉菜单。 One radio button is for 'yes' and another for 'no' 一个单选按钮代表“是”,另一个代表“否”

<input type="radio" value="true" name="staff[optquestion]">
<input type="radio" value="false" name="staff[optquestion]">

<select class="form-control" name="staff[Redesignation]"><option value=""> 
</option>

I want when a user clicks on 'yes' the dropdown below gets selected. 我想当用户单击“是”时,选择下面的下拉列表。 Here is my javascript/jquery: 这是我的javascript / jquery:

$(document).ready(function(){
    $("[name=staff[optquestion]]").change(function(){
        $("[name=staff[[Redesignation]]").toggle($(" 
[name=staff[optquestion]]").index(this)===1);
    });
});

I have placed the script in application.js but nothing happens. 我已将脚本放置在application.js中,但没有任何反应。 When I place the script in staffs.coffee I get the error "reserved word 'function'" 当我将脚本放在staffs.coffee中时,出现错误“保留字'功能'”

I know I could me mixing js and jquery here but am only starting out. 我知道我可以在这里混合js和jquery,但是只是开始。 Thanks for your help. 谢谢你的帮助。

You must be careful while selecting elements by name in jQuery. 在jQuery中按名称选择元素时必须小心。 For handling radio button inputs you should use here in your case : 要处理单选按钮输入,请在以下情况下使用:

$("input:radio[name='staff[optquestion]']")

And also remember to enclose the inputs in a form for better control. 并且还请记住以更好的控制形式将输入括起来。 So, 所以,

<form>
    <input type="radio" value="true" name="staff[optquestion]" checked="checked">
    <input type="radio" value="false" name="staff[optquestion]">
    <select class="form-control" name="staff[Redesignation]">
        <option value=""> 
        </option>
    </select>
</form>

And the JS will be : JS将是:

$(document).ready(function(){
    $("input:radio[name='staff[optquestion]']").change(function(){
        $("[name='staff[Redesignation]']").toggle();
        });
});

Since there are only two radio buttons here in use, this will work. 由于此处仅使用两个单选按钮,因此可以使用。 Incase you have more than 2 you must check with values of the radio buttons using this in the event handler. 如果您有2个以上,则必须在事件处理程序中使用按钮检查单选按钮的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM