1
\$\begingroup\$

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);
    }       
});
\$\endgroup\$
1
\$\begingroup\$

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);
\$\endgroup\$
0
\$\begingroup\$

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);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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