Alok Alok - 5 months ago 43
jQuery Question

autofocus doesn't work in textbox of dynamic content from AJAX

I've created a function in

JS
which gets
HTML
content through
AJAX
and put that in Bootstrap dialog.

Now I've added autofocus attribute to the input box which comes within dynamic HTML. The problem is I see the focus on input box for sometime and then it gets disappeared.

JS code:

function getPage(userid) {
$.ajax({
type: 'POST',
url: PAGE_URL,
data: {'userid':userid},
success: function (data) {
changeDialogContent(data);
},
error: function (e, textStatus) {
alert('Error occured while processing your request');
}
});
}


changeDialogContent
function just add the dynamic content to the Dialog as HTML.

var bootstrapmodal=$('#modelDiv');
function changeDialogContent(content) {
bootstrapmodal.html(content);
}


HTML Code of Input:

<input type="text" class="form-control input-sm someInputBox" autofocus="autofocus" value="0" placeholder="Enter Name"/>


I've also tried adding
$('.someInputBox').focus();
just after setting HTML content into Bootstrap dialog, no luck with that too.

Is there anything important I'm missing?

Answer

Here is my php code that i assume would be similar to your objective..

test.php:

<?php
        echo '<input id="my-input" type="text" class="form-control input-sm someInputBox" autofocus="autofocus" value="0" placeholder="Enter Name"/>';

?>

HTML and JAVASCRIPT CODE :

 <html>
    <head>
        <script src = "bower_components/jquery/dist/jquery.js"></script>
        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">

        <script>


            function getPage() {
                $.ajax({
                    type: 'POST',
                    url: "test.php",
                    data: {},
                    success: function (data) {
                        changeDialogContent(data);
                            document.getElementById("my-input").focus();
                    },
                    error: function (e, textStatus) {
                        alert('Error occured while processing your request');
                    }
                });
            }
            function changeDialogContent(content) {
                $('#modelDiv').html(content);
            }   

        </script>
    </head>
    <body onload="getPage()">
        <div id = "modelDiv" class="col-md-3 col-md-offset-4">
        </div>
    </body>
</html>

I used bower so the source paths of jquery and bootstrap are not cdn. And this code works really well.. I didn't encounter any error. And i am sorry that i can't provide a fiddle as it has a server request and response.. So I tested it on my own machine.

And correct me if i misinterpreted anything.

Comments