S_alj S_alj - 1 month ago 9
HTML Question

Javascript/jQuery adding forms to page, but not DOM accessible

I have this html template where I use jQuery with AJAX to fetch html forms from my server. When the user choses a specific form, it is fetched from the server placed in this div:

<div id="divform" style="border:1px solid #3e8e41"></div>

using my function:

<script type="text/javascript">

//... setting the correct URL for GETing a specific form ...
//... the function:

$("input[name=formfetch]").click(function(){ //The click event that triggers the asynchronous GET
var formurl = detailurl.replace("rootslug", $(this).attr('slug')); //The URL for the GET
$("#divform").load(formurl); //GET + load at divform
var frm = $('#theform');
document.getElementById('xpnt').value = 1; //Trying to fill the hidden fields, this fails!
document.getElementById('ypnt').value = 2;

Every form I fetch and place into "divform" will have 2 hidden fields, with ids 'xpnt' and 'ypnt'. I'll want to fill them, using my function, in every situation (in this case, I'm just putting in the values 1 and 2 as test values). I can fetch the forms, but the problem is, when I try to access these hidden fields with
to then modify their values, the browser (Chrome in this case) console shows:

(index):113 Uncaught TypeError: Cannot set property 'value' of null
at HTMLInputElement.

From what I've searched and tested, I know that the page's source won't be changed and the forms won't actually appear there (in the page source). Is the problem here that the forms I'm placing in 'divform' are not being added to the page's HTML DOM and therefore becoming "unaccessible" by these methods like
? How do I solve this issue?

PS: (I'm having no trouble in fetching the forms from the server)


I think the problem is that you are trying to search elements by ids right after executing .load, while you should actually wait until load finishes

$("#divform").load(formurl, function(resonse, status){
       // you may check status here to check for successfull load
       $("#divform").find("#xpnt").attr('value', 1).end()
                    .find("#ypnt").attr('value', 2);