Search code examples
codeigniter-3alertifyjs

cant fix Cannot read properties of undefined (reading 'length')


Hello im beginner at javascript and jquery and I'm getting this error:

Cannot read properties of undefined (reading 'length')

I don't know how to solve this. What to do to fix this error?

Here is my js file:

var fname, lname, organization, designation, email, m_number;
$('#proceedBtn').on('click', function(event) {
    fname = $('#fname').val();
    lname = $('#lname').val();
    email = $('#email').val();
    phone = $('#m_number').val();
    organization = $('#organization').val();
    designation = $('#designation').val();
    //set it to true
    var isProceed = true;

    if (fname.trim() === "" || fname.length < 2) {
        alertify.error('Please input your first name');
        isProceed = false;
    }

    if (lname.trim() === "" || lname.length < 2) {
        alertify.error('Please input your last name');
        isProceed = false;
    }
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var emailValid = re.test(String(email).toLowerCase());

    if (email.trim() === "" || email.length < 3 || !emailValid) {
        alertify.error('Please check your email');
        isProceed = false;
    }

    if (m_number === "" || m_number.length < 3) {
        alertify.error('Please input your phone');
        isProceed = false;
    }
    if (organization.trim() === "" || organization.length < 2) {
        alertify.error('Please input your organization');
        isProceed = false;
    }

    if (designation.trim() === "" || designation.length < 2) {
        alertify.error('Please input your designation');
        isProceed = false;
    }


    if (isProceed) {
        procceedBTN();
        // $('html, body').animate({scrollTop: '0px'}, 0);
    }
})

Solution

  • You have initiated some variables in the top, but not defined/assigned any value to them

    var fname, lname, organization, designation, email, m_number;

    note that, these variables have value undefined

    in the starting of your function, you assigned some values to fname, lname and email, But still m_number is undefined.

    In your whole code you never assigned any value to m_number

    but in your code at:

     if (m_number === "" || m_number.length < 3) {
        alertify.error('Please input your phone');
        isProceed = false;
    }
    

    you are asking to check the length of an undefined variable

    m_number.length //this is the error
    

    You can simply remove this part of code or can define a value to m_number

    Like

    m_number = ''