0
formatPhone:function(component, event, helper) {
    var phoneValue = component.find("phoneId");
    phoneValue = Array.isArray(phoneValue) ? phoneValue[0].get("v.value") : phoneValue.get("v.value");

    if(phoneValue.length > 3 && phoneValue.length < 6 && (!phoneValue.includes("(") &&  !phoneValue.includes(")"))){

        phoneValue[0].set("v.value","("+phoneValue.substr(0,3)+") "+phoneValue.substr(3,phoneValue.length));
    }
0

It looks like you're handling an array return from component.find() twice, and also taking its value when you want the element itself.

First, you do this:

phoneValue = Array.isArray(phoneValue) ? phoneValue[0].get("v.value") : phoneValue.get("v.value");

which gives you the v.value property of the first element of phoneValue, which you use in the following logic. But then you also do

phoneValue[0].set("v.value" ...)

while phoneValue is now set to the value of the first element returned by component.find(), not the element itself. You need to hold on to that element value before you call get("v.value"), so that you can later call set(), and you need to not use array access a second time.

4
  • Thanks David for the response. I tried this. Yet, I receive the same error - component.find("phoneId").set("v.value","("+phoneValue.substr(0,3)+") "+phoneValue.substr(3,phoneValue.length)); – Nishanth Dec 11 '19 at 2:01
  • @Nishanth Perhaps component.find("phoneId") returns an Array? – David Reed Dec 11 '19 at 2:08
  • That's right... – Nishanth Dec 11 '19 at 2:11
  • So you need to use that expression you already have to get the element you want. – David Reed Dec 11 '19 at 2:29
0

After the second line, phoneValue is now just a String, not a SecureComponent. I suggest this instead:

var phone, phoneCmp = component.find('phoneId');
if(phoneCmp) {  // we have an object?
    if(phoneCmp.length) {  // this is an array
        phoneCmp = phoneCmp[0];
    }
    if(phoneCmp.get) { // this is a component?
        phone = phoneCmp.get('v.value');
        if(phone && phone.match(/^\d{3,}$/)) { // only digits, at least 3?
            phoneCmp.set('v.value', '('+phone.substring(0,3)+')+phone.substring(3));

    }
}

Your main problem was that you "forgot" your component reference, so you couldn't call the set method, because you were trying to call that on a String. Always be careful to keep track of what's in your variables.

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.