Reputation: 227
jQuery $("#element").focus(); function does not work the first time in v-if div.
Hello i have the next issue with Vue js. I have a div which is hidden at load with v-if. When the v-if condition is true the div is displayed but the input field inside that div does not want to focus. $("#element").focus();. This happens only the first time, after the div is displayed .focus() works
ex. I have this function in methods
addBox: function (event)
{
this.boxes.push({id: 1, name: 'Name', weight: 10 }); // Default is empty array. Comes true when i call this function and the div with #upc input becomes active and displayed
$("#upc").focus(); // When the first time boxes becomes true $("#upc").focus(); does not work. Once is displayed it works after.
}
Html
<div class="row" v-show="boxes.length > 0">
<div class="col-md-6">
<input v-model="upc" type="text" class="form-control" name="upc" placeholder="Scan UPC here" id="upc" @keyup.13="scan">
</div>
</div>
Once this.boxes.lenght boxes > 0 calling $("#upc").focus(); is working and will focus the input field.
Upvotes: 1
Views: 1244
Reputation: 14677
Two things to try:
Use Vue's nextTick to make the focus call happen on the next DOM update (once the DOM is fully populated with the results of your view model change):
Vue.nextTick(function() { $('#upc').focus(); });
Try vue-focus which binds the focus operation to a model property (which means you can get rid of jQuery).
Upvotes: 6