Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have to enable/disable multiple inputs when a select change. It works but I want to do it better. How can I improve my code?

$("#street_type").on("change", function(event){
    if( $(this).val() == 1){
        $("#clase_via").prop('disabled', true);
        $("#nombre_via").prop('disabled', true);
        $("#numero_via").prop('disabled', true);
        ...
        $("#indicaciones").prop('disabled', true);
    }
    if( $(this).val() == 2){
        $("#clase_via").prop('disabled', false);
        $("#nombre_via").prop('disabled', false);
        $("#numero_via").prop('disabled', false);
        ...
        $("#indicaciones").prop('disabled', false);
    }       
});
share|improve this question

2 Answers 2

Create array with id's of needled input's:

var inputs = ["clase_via", ...], i, count;
for (i = 0, count = inputs.length; i < count; i += 1){
    $(inputs[i]).prop("disabled", true);
}

Add "data" attribute for needled input's:

<input type='text' data-lockable="true"/>
$("input [data-lockable='true']).prop("disabled", true);

Place all input's into one block and call jQuery as:

$("#maindiv > input").prop("disabled", true);
share|improve this answer

The easiest way is putting a class for all the items you want enabled/disabled:

$(".class_name").prop('disabled', true);` and `$(".class_name").prop('disabled', false);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.