1

I am trying to have my form fields submit after the onchange event.

The Json value returned looks like this:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } 

I am going to add an array to this sting to specify any other fields (such as 'total') which also need updating, like so:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error", "toUpdate": [ { "name":"p_total_data1" , "value":"999" } ] } ] } 

So I will only want to run the update total script when the toUpdate array exsists. My issue is if I use an if statement like

if(typeof results.data[0].toUpdate[0].name == 'undefined'){}

or

if(null != results.data[0].toUpdate[0].name){}

or

if(results.data[0].toUpdate[0].name.length){}

All give the error "results.data[0].toUpdate[0].name is undefined". How can I test whether it is defined?

0

2 Answers 2

4

You need to check to check for the existence of results.data[0].toUpdate before you attempt to access its properties:

if (results.data[0].toUpdate && results.data[0].toUpdate[0].name){
  // perform the update
}

If the first condition evaluates to false (or any "falsy" value), the && operator will short-circuit and won't evaluate the second condition at all, preventing the error you're seeing.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the optimal way, this way if toUpdate is undefined the second expression wont be evaluated, as its not even eveluated no error is thrown by trying to access property of nonexisting 'toUpdate'.
1

Check all the elements of result object either is undefined or not

if(results !='undefined' && results.data!='undefined' && results.data[0]!='undefined' && results.data[0].toUpdate != 'undefined' && results.data[0].toUpdate[0] != 'undefined' && typeof results.data[0].toUpdate[0].name != 'undefined')
{
  //
}
else
{
 //
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.