I have a dynamically generated form which I get from an asynchronous AJAX call and I have some settings provided in a JSON object. I want to target one field specifically with jQuery, so I load the JSON data to a JS variable to work with it:
var jsonData = {{response.write(session.j_jsondata, escape=False)}};
/*
I'm using Web2Py, so the part between the double curly braces is equal to:
{'fields': [{'required': 'true', 'type': 'mtext', 'name': 'desc'}]}
*/
The data gets loaded correctly to the variable, but then when I want to target something with a name from jsonData.fields[somenumber].name it doesn't work.. I've tried it like this:
jQuery("form [name="+jsonData['fields'][i]['name']+"]")
I get no error. Any ideas why it's not targeting the expected element? Thanks!
Edit: I tried changing the structure a bit. Instead of using name I chose ID (I updated the template view as well ofc) and switched to
jQuery("#"+jsonData['fields'][i]['name'])
but still no cigar. It probably has some problems with tha fact that the field is generated after an AJAX call, but that's wierd because the script is called after the form is generated. So the last thing that happens is the execution of this script which targets the form element, yet it doesn't work. Sorcery.
ihave the correct value? Since you don't know (I assume) whether the selector is generated correctly or not, set a breakpoint and expect the variables. To learn how to do that (if you not do already), have a look at netmagazine.com/tutorials/javascript-debugging-beginners.console.log("form [name="+jsonData['fields'][i]['name']+"]")just before the selection and have a look what the output is. Is the selector correct? And are you executing this call when the form exists (since it is loaded via Ajax)?