1

I have a problem with jQuery focus(). From the selector, I can target the element, and can change the css of the element (for example display:none). But making the item to be focused doesn't work.
A video demo. Switch on HD to see more clearly.
I used AngularJs for the display.

The thing I am doing is quite complicated to explain. Demo here
Code can be found here

How to use the app: click in the first text field of the form. There will be a new form generated. As you can see, when the new form is generated, the first input field will be focused. Next you choose in the new form the 2nd select field, choose dropdown or option. Then you click on the first inputfield, there will be a new form generated. The problem I have here is that it doesn't focus on the new one.

How I focus:

$scope.addSubItem = function(index)
    {
        var newSubItem = [];
        var data = $scope.inputData;
        newSubItem.push("");
        newSubItem.push(0);
        newSubItem.push("hour");
        newSubItem.push("");
        $scope.items[index][6].push(newSubItem);
        var itemToBeFocus = "#subItem" + index +"form:last-child input:first-child";
        setTimeout(function(){
            $(itemToBeFocus).focus(); //here
        },0);
    }


phuwin
  • 3,130
  • 4
  • 26
  • 49

1 Answers1

1

i guess you have missed a _ space here before "form:

var itemToBeFocus = "#subItem" + index +" form:last-child input:first-child";
angular.element(itemToBeFocus).focus(); //here

and instead of setTimeout try with angular.element() jqLite object wrapper.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • Without `setTimeout` the `.focus()` is called before the new item is added into the array, so the wrong item will be focused. I tried `angular.element`, but it doesn't work like I want. – phuwin Oct 16 '15 at 12:27
  • I remove it because you had a delay time to 0 in the timeout function. @PhuNguyen – Jai Oct 16 '15 at 12:29
  • 1
    That is well and good if that works for you because of a short code snippet i just explained it the way i wanted it to be yet you can keep the setTimeout that won't create any problem but it helps in angular, as this is just for having focus on a specific element only. – Jai Oct 16 '15 at 12:34
  • You are awesome. Thanks for your help. Have a nice day! – phuwin Oct 16 '15 at 12:37