sourceplaze
sourceplaze

Reputation: 333

How do toggle elements when option is selected?

I want to toggle checkboxes based on the option chosen from the select. Here is my selector inside insertUser template:

<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>

And I have check box as follow:

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

I want to view the checkbox when Admin is selected from the selector and hide it when Normal User is selected, How should I go about doing it?

Upvotes: 0

Views: 58

Answers (2)

blueren
blueren

Reputation: 2860

The meteor way:

  1. Wrap the checkbox inside an if block
  2. Set a session var based on the dropdown.
  3. If the user is admin, show the checkbox.

template:

    <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>

helper:

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);
});

Upvotes: 1

Subash
Subash

Reputation: 816

You can use hide() and show() method

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

FIDDLE

Upvotes: 0

Related Questions