I am trying to change a text to a text box. If a user clicks the text, it will change to a test box and so they can edit the content. I have done that. I am able to set the focus by below code.
{{input value=animal.name autofocus=true}}
It only works for the first time. If I focus-out, the text box will again change to text content. If I click the text again, I am able to see the text box, but it is not in focus. Below is the code I am trying.
Component file:
import Ember from 'ember';
export default Ember.Component.extend({
isTextBox: false,
actions: {
editTest() {
this.set('isTextBox', true);
}
},
focusOut() {
this.set('isTextBox', false);
},
});
Template file:
{{yield}}
<center><h2>
<div onclick = {{action 'editTest'}}>
{{#if isTextBox}}
{{input value=animal.name autofocus=true}}
{{else}}
{{animal.name}}
{{/if}}
</div>
</h2></center>
I am new to ember and I trying to do the focus without using jQuery.
Here is the twiddle https://ember-twiddle.com/d832c6540ba94901a6c42d5bb3cfa65e?openFiles=templates.components.text-input.hbs%2Ctemplates.components.text-input.hbs.
You can do this in Plain Old Javascript as follows:
didRender(){
// This works but is not very ember-ish
// document.getElementById('cat-text').focus();
// For a component, you can do this
this.get('element').querySelector("#cat-text").focus();
}
This assumes you have an input like this:
{{input id='cat-text' value=animal.name }}
Ember 2.13+ is no longer dependent on jQuery (although some of the add-ons that you use may be), so you have the possibility of eliminating 35kb (min + gzip) that jQuery would add to the payload of your app.
To expand on kumkanillam's answer you can just set the focus at the end of the render lifecycle if it's rendering a textbox. Since you've only got one text input in your component you can just find it with a selector. No need to worry about using jQuery here that's what it's there for so it is the Ember way.
didRender(){
if(this.get('isTextBox')){
this.$('input[type=text]:first').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