选择选项后如何切换元素?

时间:2017-12-28 23:29:31

标签: jquery meteor

我想根据从select中选择的选项切换复选框。 这是insertUser模板中的选择器:

<div class="form-group">
    <label for="userType">User Type:</label>
    <select class="form-control" id="userType">
        <option value="admin">Admin</option>
        <option value="user">Normal User</option>
    </select>
</div>

我的复选框如下:

<div class="checkbox">
    <label><input type="checkbox" value="rm">Remove Users</label>
</div>

我想查看从选择器中选择管理员时的复选框,并在选择普通用户时隐藏它,我应该怎么做呢?

2 个答案:

答案 0 :(得分:1)

流星的方式:

  1. 将复选框包含在if块
  2. 根据下拉列表设置会话变量。
  3. 如果用户是管理员,请显示复选框。
  4. <强>模板:

        <template name="wow">
        <div class="form-group">
            <label for="userType">User Type:</label>
            <select class="form-control" id="userType">
                <option value="admin">Admin</option>
                <option value="user">Normal User</option>
            </select>
    
    <!-- here is the if block -->
    
    {{#if isAdmin}}           
    <div class="checkbox">
        <label><input type="checkbox" value="rm">Remove Users</label>
    </div>
    {{/if}}
    
    <!-- if block ends -->
    
        </div>
        </template>
    

    <强>助手:

    Template.wow.helpers({
        // returns only when isAdmin is true.
        isAdmin: function(){
            return Session.get("isAdmin");
        }
    });
    
    
    Template.wow.events({
        // check for the change in value of the dropdown. If admin is chosen, set the isAdmin session variable.
    
        'change #userType'(event){
            if(event.target.value == 'Admin'){
                Session.set('isAdmin', true);
            }
        }
    });
    
    //For the sense of completeness, unset the used session variable when the template gets destroyed.
    
    Template.wow.onDestroyed(function(){
       Session.set("isAdmin", undefined);
    });
    

答案 1 :(得分:0)

您可以使用hide()show()方法

$(document).ready(function () {
    $('#userType').on('change', function () {
        if ($(this).val() == 'admin') {
            $('.checkbox').show();
        } else {
            $('.checkbox').hide();
        }
    });
});

FIDDLE