Vémundr Vémundr - 3 months ago 9
HTML Question

Inject a form with Ajax, get its input value

Main page div is updated with an Ajax request. The updated html contains a form with input fields, a button, and another Ajax script to submit that form. While it is possible to initiate the second script by pressing the button in the injected form, the script does not seem to find form inputs by id.
I read about the .on() method of JQuery, but it only seems to provide access to dynamically updated functions, not elements.
How do I get the input element by ID, after this element got injected into the code with an Ajax request?

Main page:

<div id="output"></div>
<span id="call_account">Account</span>


$("#call_account").click(function(){
$.get('/accounts/login/', {}, function(data){
$('#output').html(data);
});
});


Injected into #output html:

<input id="id_username" name="username" type="text">
<input id="id_password" name="password" type="password">
<span id="account_submit">Submit</span>


$("#account_submit").on("click", function() {

var id_username = $('#id_username').val();
var id_password = $('#id_password').val();

$.ajax({
type:"POST",
url:"/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function(data){
$('#output').html(data);
}
});

});
});


id_username and id_password are undefined when I try to submit the form.

edit:
Thanks to answers from the guys below I was able to get it to work. I also made a jsfiddle simulation of the problem in the process: https://jsfiddle.net/hn1Lrkzs/
Hope it helps someone in the future, I had trouble finding a direct answer, and lacked understanding to get the thing from help files.

Answer

Enclose your js inside document.body

    <script>
    $(document.body).on("click", "#account_submit", function() {


                var id_username = $('#id_username').val();
                var id_password = $('#id_password').val();

                $.ajax({
                     type:"POST",
                     url:"/accounts/login/",
                     data: {
                            'username': id_username,
                            'password': id_password,
                            },
                     success: function(data){
                             $('#output').html(data);
                     }
                });

            });


    </script>
Comments