0

I am working on a custom live validation for a form element - textarea. I am trying to add a focus listener in a for loop for every field from my array.

Code:

var fieldIds = ["field10","field8","field6","field5","field4"];
//On focus out/focus in
    for (var i=0; i<fieldIds.length;i++){
            $( "#"+fieldIds[i] ).focusout(function() {
                focusOutValidation(fieldIds[i]);
            });
            $( "#"+fieldIds[i] ).focus(function() {
                focusInValidation(fieldIds[i]);
            });
        }

    function focusOutValidation(fieldId){
        if ($('#'+fieldId).val().length == 0){
                $('#'+fieldId).removeClass('LV_valid_field');
                $('#'+fieldId).addClass('LV_invalid_field');
            }else{
                $('#'+fieldId).addClass('LV_valid_field');
                $('#'+fieldId).removeClass('LV_invalid_field');
            }
        }

    function focusInValidation(fieldId){
        if ($('#'+fieldId).val().length == 0){
            $('#'+fieldId).removeClass('LV_invalid_field');
        }

For some reason, during debugging, when I focus any of the fields from the array, the script goes to the focusInValidation function, but fieldId is undefined. Any idea?

Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103
  • Is there really no way you can use a common class for this? – Rory McCrossan Dec 10 '15 at 14:01
  • BTW, jQuery does the loop for you: `var myFields = jQuery( '#field10,#field8,#field6,#field5,#field4' ); myFields.focus( /* … */ ); myFields.focusout( /* … */ );` – feeela Dec 10 '15 at 14:01
  • 1
    The reason your code doesn't work is in the answer of the above so-dupe question. To improve code use `var fieldIds = ["field10", "field8", "field6", "field5", "field4"]; var selector = '#' + fieldIds.join(', #'); $(selector).on('focus blur', function () { if($(this).val().length === 0) { $(this).addClass('LV_invalid_field').removeClass('LV_valid_field'); } else { $(this).removeClass('LV_invalid_field').addClass('LV_valid_field'); } });` – Tushar Dec 10 '15 at 14:05
  • Thank you, it works and it is much more efficient and clean. – Ondrej Tokar Dec 10 '15 at 14:14
  • 1
    I don't think the linked answer is really the best way to solve this. There is no need for anonymous functions here. – Rob Foley Dec 10 '15 at 14:15

0 Answers0