3

This question already has an answer here:

I have a aura:if expression that renders a inputNumber field after checkbox is clicked and certain other criteria matches.

Now, I want that inputNumber to be focused (and set certain attributes, like inputMode : numeric) after I click the checkbox.

The problem is that component.find("amount").getElement() returns null. There is a potential workaround to use setTimeout, but it's not elegant and breaks on iOS (Mobile Safari only pops keyboard if focus() event was received synchronously).

Code below.

Component:

<input
  value="{! v.foo.Selected }"
  name="{!v.foo.Key + v.index}"
  type="checkbox"
  id="{! v.foo.Key + v.index }"
  onclick="{! c.selectfoo }"
  data-value="{! v.foo.Name }"
  data-key="{! v.foo.Key }"
  aura:id="fooBox" />
<aura:if isTrue="{! and(v.foo.AmountRequired, v.foo.Selected) }">
<div class="slds-form-element__control">
  <ui:inputNumber 
    class="slds-input"
    format="$###,###,###"
    placeholder="$"
    aura:id="amount" 
    value="{! v.foo.SumAssured }"
    keyup="{! c.moveFocus }"/>
</div>
</aura:if>

Controller:

selectBenefit: function(component, event, helper) {
    var selected = component.get('v.Benefit.Selected');
    component.set('v.Benefit.Selected', !selected);
}

Renderer:

({
    rerender : function(component, helper){
        this.superRerender();
        var amount = component.find("amount");

        console.log(amount);
        console.log(amount.getElement()); //returns null

        //below somewhat works
        if (amount.isValid()){
            window.setTimeout(
                $A.getCallback(function() {
                    if (component.isValid() && amount.isValid()) {
                        var input = amount.getElement();
                        console.log(input);
                        input.focus();
                        input.setAttribute("pattern", "\\d*");
                        input.setAttribute("inputmode", "numeric");  
                    }
                }), 200
            );   
        }
    }
})

EDIT: Tried different approach and still got same race condition problem. After toggling 'slds-hide' class on an element, focus() doesn't execute, most likely because it's not visible yet:

$A.util.toggleClass(component.find("amountContainer"), "slds-hide");
    if( component.get('v.Benefit.AmountRequired') && !selected ){  
      console.log(component.find("amount").getElement())
}

marked as duplicate by Renato Oliveira, Vijay Ganji, Pranay Jaiswal, Mohith Shrivastava, Ratan Paul Jun 16 at 13:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.