I have a Model that has 1 input. Also, I have a Collection. Now, when I add a model to the collection, I want to set the focus to it's input. To be precise, I need to set the focus on the newly created model view's input.
However, I can't seem to get it to work. Here's my function that adds the model's view to the collection view:
addOne: function(InvoiceItem) {
var view = new InvoiceItemView({model: InvoiceItem});
this.$('tr[data-id="'+InvoiceItem.get('after')+'"]').after(view.render().el);
this.$('tr[data-id="'+InvoiceItem.cid+'"]').css('background', 'green');
this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
},
The problem is, the third call: this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
does not do anything. And it's weird, because it seems that I can only do DOM manipulation on the root element tr
, and on nothing else besides that.
It seems to me that jQuery doesn't know that the element exists, which is weird, because when I do alert(this.$('tr[data-id="'+InvoiceItem.cid+'"] input').length)
I get 1, which indicates that the element exists.
What it is that I am doing wrong here?
Using _.defer fixed my problem:
var $this = this;
_.defer(function(){
$this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
});
Instead of this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
try this
$(view.render().el).find('input').focus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With