Dropout
Dropout

Reputation: 13866

Targeting an element with jQuery depending on JSON data

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.

Upvotes: 1

Views: 105

Answers (2)

Terence Jefferies
Terence Jefferies

Reputation: 358

After testing on a local webpage, I noticed that you cannot have a space between the form and opening square bracket, so your selector should read:

jQuery("form[name="+jsonData['fields'][i]['name']+"]")

Cheers,

Terence.

Upvotes: 2

shere
shere

Reputation: 101

Maybe it's because the quotations for the attribute selector is missing. Try this:

$('form [name="'+jsonData['fields'][i]['name']+'"]')

Upvotes: 2

Related Questions