-1

I have a jQuery validation function for a form. Validation logic is pretty the same for all fields, what varies are field names. Can I pass html element's ID as an method parameter? I mean - I know I can, but how to place it after #?

function validateFieldName(){
        var nameFieldLength = $("#nameField").val().length;
        if(cgLength < 3 || cgLength > 15){
            $("#nameFieldLab").html("error");
            $("#nameFieldLab").show();
        }else{
            $("#nameFieldLab").hide();
        }
}

What I wan't to have is single function, something like this:

function validateField(formField, errorLabel){
            var fieldLength = $("#formField").val().length;
            if(cgLength < 3 || cgLength > 15){
                $("#errorLabel").html("error");
                $("#errorLabel").show();
            }else{
                $("#errorLabel").hide();
            }
    }
jarosik
  • 4,136
  • 10
  • 36
  • 53

2 Answers2

1

Try simple string concatenation:

function validateName(id) {
  var nameFieldLength = $("#" + id).val().length; //Here.
  ....
}
K K
  • 17,794
  • 4
  • 30
  • 39
0

Id pass not a good one Better pass this

function validateName(that){
        var nameFieldLength = $(that).val().length;
        if(cgLength < 3 || cgLength > 15cgLength){
            $(that).html("error");
            $(that).show();
        }else{
            $(that).hide();
        }
}
prasanth
  • 22,145
  • 4
  • 29
  • 53