Reputation: 31
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
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
Reputation: 45589
var hideFields = function () {
var $fields = $('#foo, #bar, #lorem, #ipsum');
$fields.toggle(!($('#select').val() === 'something'));
};
hideFields();
Upvotes: 0
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