2017-05-18 8 views
1

Javascriptのフォーカスが自分のコードで機能していません。JavaScriptのフォーカスが機能しない

はHTML

<div class="col-md-6" style="border:none; margin-top:2px; padding-right:5px"> 
    <input type="text" id="edtunt" ng-model="Unit" class="form-control" placeholder="Edit Unit" /> 
</div> 

Javascriptを

var textbox = document.getElementById('edtunt'); 
//document.getElementById("edtunt").focus(); 
document.getElementById("edtunt").focus(); 
$scope.Unit = unit.name; 

答えて

1

あなたのコードは動作します:

document.getElementById('edtunt').focus();
<div class="col-md-6"> 
 
    <input 
 
    type="text" 
 
    id="edtunt" 
 
    ng-model="Unit" 
 
    class="form-control" 
 
    placeholder="Edit Unit"> 
 
</div>

また、あなたのAngularJSのアプリケーション内で、あなたはautofocus属性を追加することができます。

angular 
 
    .module('MyApp', []) 
 
    .controller('MyController', function() {});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="MyApp" ng-controller="MyController"> 
 
    <div class="col-md-6"> 
 
    <input 
 
     autofocus 
 
     type="text" 
 
     id="edtunt" 
 
     ng-model="Unit" 
 
     class="form-control" 
 
     placeholder="Edit Unit"> 
 
    </div> 
 
</div>

1

使用でtabindex = "0"

0

実際にフォーカス可能なdiv要素を作るためのあなたのコードはうまくいくはずです。あなたはなぜ、質問、:の代わりに

var textbox = document.getElementById('edtunt'); 
document.getElementById("edtunt").focus(); 

:私は文書全体にフォーカスを設定する前にロードされていることを確認作っているために働いて何

var textbox = document.getElementById('edtunt'); 
textbox.focus(); 

。これを行う簡単な方法は、このコピーペーストのJQueryコードを使用することです。

$(document).ready(function() { 
    var textbox = document.getElementById('edtunt'); 
    textbox.focus(); 
}); 

希望する場合があります。

関連する問題