thom
thom

Reputation: 31

JQuery - Show/Hide a group of fields

I want to show or hide some fields using a select's value as criteria. I don't want to repeat myself wrinting the loop again just to show and hide fields. I want to use the same loop code to show or hide. What's the best approach?

hideFields = function () {
    var fields = $(['#foo', '#bar', '#lorem', '#ipsum'])
        showHide = function (action) {
            if (action === 'show' || action === 'hide') {
                action = action + '();';
                fields.each(function (index, value) {
                    $(value).parent()
                        .parent()
                        .action(); // call show||hide here... not working...
                });
            }
        };

    if ($('#select').val() === 'something') {
        showHide('hide');
    }
    else {
        showHide('show');
    }
};

hideFields();

Thanks.

Upvotes: 3

Views: 2399

Answers (3)

Charlie
Charlie

Reputation: 1072

I think this will work. Make sure you use option:selected to get the value of the select.

function hideFields() {
    var fields = '#foo, #bar, #lorem, #ipsum';
    if ($('#select option:selected').val() === 'something') {
        $(fields).show();
    } else {
        $(fields).hide();
    }
}
hideFields();

Upvotes: 0

Shef
Shef

Reputation: 45589

var hideFields = function () {
    var $fields = $('#foo, #bar, #lorem, #ipsum');
    $fields.toggle(!($('#select').val() === 'something'));
};

hideFields();

Upvotes: 0

user915495
user915495

Reputation:

You can use jQuery's toggle() method to show and hide elements:

$(".fields").toggle();

That way, you don't have to worry about their state and have jQuery figure out if they need to be hidden or not.

You can also pass in a boolean to the method which will only show or only hide the elements:

$(".fields").toggle(true); // Shows elements, equivalent to show()
$(".fields").toggle(false); // Hides elements, equivalent to hide()

And if you need to do some extra logic you can always query the elements' CSS property using $().css() and decide what to do from there.

Upvotes: 1

Related Questions