Reputation: 71
(new to JQuery) I have a list of around 20 or so elements that need to be disabled when the page loads. The list of elements contains the full range of HTML <input> elements, each having distinct IDs that follow a general naming convention.
$('#rmX\\.val').prop("disabled",true);
$('#rmX\\.unit').prop("disabled",true);
$('#rmX\\.ba').prop("disabled",true);
$('#rmX\\.sms\\.opt').prop("disabled",true);
$('#rmX\\.sms\\.val').prop("disabled",true);
$('#rmX\\.sms\\.car').prop("disabled",true);
$('#rmX\\.em\\.opt').prop("disabled",true);
$('#rmX\\.em\\.val').prop("disabled",true);
$('#rmX\\.off\\.opt1').prop("disabled",true);
$('#rmX\\.off\\.opt2').prop("disabled",true);
$('#rmX\\.off\\.val').prop("disabled",true);
$('#rmZ\\.end\\.vald').prop("disabled",true);
$('#rmZ\\.end\\.valw').prop("disabled",true);
$('#rmZ\\.end\\.valm').prop("disabled",true);
$('#rmZ\\.end\\.valy').prop("disabled",true);
$('#rmZ\\.date').prop("disabled",true);
$('#rmZ\\.time').prop("disabled",true);
$('#rmZ\\.ap').prop("disabled",true);
$('#evt\\.sec\\.opt2').prop("disabled",true);
$('#evt\\.sec\\.val21').prop("disabled",true);
$('#evt\\.sec\\.val22').prop("disabled",true);
Is there a way to make this list more efficient or is this just the way ya'll do it.
(PS. surprised there isn't a "best-practices" tag available.)
EDIT: Changed "hidden" from original question to "disabled" as is displayed in my code.
Upvotes: 0
Views: 69
Reputation: 19797
An alternate approach is if the fields are grouped together you could use a parent object such as a div or better still a field set.
For a quick and dirty example see this fiddle
Upvotes: 0
Reputation: 186083
You can store those strings inside an array:
var arr = [ '#rmX\\.val', '#rmX\\.unit', ... ];
and then:
$.each( arr, function ( i, val ) {
$( val ).prop( 'disabled', true );
});
This won't make it more efficient, but it removes the code repetition.
Upvotes: 0
Reputation: 13248
Add a class and then do this way:
$('.hideClass').hide();
(Or)
$("#rmX\\.val, #rmX\\.unit, #rmX\\.ba, #rmX\\.ba").hide();
Upvotes: 0
Reputation: 54636
Why not add a class canBeDisabled
to all the elements in your #evt
that you want to disable?
$("#evt .canBeDisabled").prop("disabled", true);
Upvotes: 5