0

I am trying to move the focus to lightning-input field when clicked on tag. I am getting the value for the data-id set in the tag but focus() function isn't working. Also If I hardcode the value of data-id then it work fine as expected, I need it to make dynamically!

moveFocus(event){
        const field=event.currentTarget.dataset.id;
        console.log('Moving focus to First Name Legal....'+field);
        this.template.querySelector(`[data-id="${field}"]`).focus();            
}
2
  • Give that input field class and then try using className like this.template.querySelector('.classsName']`).focus() Mar 20, 2023 at 10:57
  • @Harshit :To help you in a better way, Can you please add HTML in your answer and on which event is moveFocus function called ? It appears that you have 2 fields with same data-id and you are always getting the wrong one in the selector.
    – Rohit
    Mar 20, 2023 at 13:09

1 Answer 1

0

We can handle this by either having same data-id for the elements(tag and lightning-input) in this case or a particular format to relate them.

Both the approaches are described below :

1. Same data-id attribute

Here , we can add additional class for input selection as below:

HTML:

<lightning-button class="slds-m-left_xx-small slds-m-bottom_small slds-m-top_x-small"
  variant="brand"
  label="Focus Input"
  data-id="myField"
  onclick={handleClick}>
</lightning-button>

<lightning-input class="inp-cls" type="text" data-id="myField" label="Enter some text" placeholder="type here..."></lightning-input>

We have added css class inp-cls for selecting the particular input associated.

JS :

handleClick(event) {
    const fieldId = event?.currentTarget?.dataset?.id;
    console.log("fieldId1",fieldId);
    this.template.querySelector(`.inp-cls[data-id="${fieldId}"]`).focus();
  }

2. Related data-id attribute

Here , we can append a string to the lighting-input element along with the data-id as below:

HTML:

<lightning-button class="slds-m-left_xx-small slds-m-bottom_small slds-m-top_x-small"
  variant="brand"
  label="Focus Input"
  data-id="myField"
  onclick={handleClick}>
</lightning-button>

<lightning-input class="inp-cls" type="text" data-id="myField_input" label="Enter some text" placeholder="type here..."></lightning-input>

JS:

handleClick(event) {
    const fieldId = event?.currentTarget?.dataset?.id;
    console.log("fieldId2",fieldId);
    this.template.querySelector(`[data-id="${fieldId}_input"]`).focus();
  }

I would prefer 1st approach just because its straight forward.

You must log in to answer this question.