user6315833
user6315833

Reputation: 3

ng-repeat and focus inputs

I have a list of buttons and inputs generated by ng-repeat, and I want the following functionality : when I click a button it focuses on the following input.

If I use:

    <div>
        <button class="btn btn-sm chat-option chat-option-add but-0" style="padding: 0px;border-radius: 50%;"></button>
        <input type="text" class="input-0" style="color:black;">
    </div>

    <div>
        <button class="btn btn-sm chat-option chat-option-add but-1" style="padding: 0px;border-radius: 50%;"></button>
        <input type="text" class="input-1" style="color:black;">
    </div>`enter code here`
 <script>
    $('.but-0').click(function () {
        $('.input-0').focus();
    });
    </script>

    <script>
    $('.but-1').click(function () {
        $('.input-1').focus();
    });
    </script>

it works fine. but if i want to use ng-repeat with those scripts :

   <div ng-repeat="f in testFocus">
            <button class="btn btn-sm chat-option chat-option-add but-{{$index}}" style="padding: 0px;border-radius: 50%;"></button>
            <input type="text" class="input-{{$index}}" style="color:black;">

        </div>

it doesn't work for me - clicking the button does not focus the input at all.

thanks

Upvotes: 0

Views: 1024

Answers (1)

Saad
Saad

Reputation: 952

You have to bind event to an already existing element.

<button class="btn btn-sm chat-option chat-option-add but-{{$index}}" style="padding: 0px;border-radius: 50%;">button</button>
<input type="text" class="input-{{$index}}" style="color:black;" />
$(document).on('click', '.but-0', function () {
    $('.input-0').focus();
});

$(document).on('click', '.but-1', function () {
    $('.input-1').focus();
});

In angular you can do it more elegantly by taking help of ng-click on the button.

<button class="btn btn-sm chat-option chat-option-add" ng-click="buttonClicked($index)" style="padding: 0px;border-radius: 50%;">button</button>
<input type="text" class="input-{{$index}}" style="color:black;" />
$scope.buttonClicked = function($index) {
    $('.input-'+ $index).focus();
}

See this DEMO

Upvotes: 1

Related Questions