2017-05-18 1 views
1

Javascript-Fokus funktioniert nicht in meinem Code.JavaScript Focus funktioniert nicht

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; 

Antwort

1

Ihr Code funktioniert:

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

Auch innerhalb Ihrer AngularJS Anwendung, können Sie das autofocus Attribut hinzufügen:

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

Verwendung tabindex = "0" für div machen fokussierbarem

0

Tat Ihr Code sollte funktionieren. Nur eine Frage, warum Sie tun:

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

Statt:

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

Was für mich gearbeitet ist dafür, dass das gesamte Dokument vor Fokuseinstellung geladen wird. Eine sehr einfache Möglichkeit, das zu tun, wird mit dieser Kopie einfügen JQuery-Code:

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

Hope this helfen könnte!

Verwandte Themen