Question

I have list of objects with key value & pair.when I am separating those to display each information on a specific field . I am getting type error data.validation[i].user is undefined But I have checked the variables have been assigned a value.

var data = {validation:[
{"user":"user may not be empty"},
{"date":"Date may not be null"},
{"mobile":"passengerMobile may not be empty"},
{"mobileSize":"passengerMobile size must be greater than 11"},
{"name":"passengerName may not be empty"},
{"nameSize":"passengerName size must be between 2 and 30"},
 ]};

var size = data.validation.length;

for(var i =0;i<=size;i++){
if(data.validation[i].user){
 $("#username").html("<p>"+data.validation[i].user+"</p>");
  }
  if($("#mobile").val().length == 0){
    $("#mobilesize").html("<p>"+data.validation[i].mobile+"</p>");
    }
    else if($("#mobile").val().length >= 1){
    $("#mobilesize").html("<p>"+data.validation[i].mobilesize+"</p>");
    }
  }

$("#mobile") indicates an input field Id

Any Ideas are warm welcome

Was it helpful?

Solution

use only less than in tour condition here. because it start form 0,1,2,....

for(var i =0;i<size;i++)

you have length 6, but when fetching last then this should be

data.validation[5].user

You Correct code should be:

  var size = data.validation.length;

    for(var i =0;i<size;i++){
    if(data.validation[i].user){
     $("#username").html("<p>"+data.validation[i].user+"</p>");
      }
      if($("#mobile").val().length == 0){
        $("#mobilesize").html("<p>"+data.validation[i].mobile+"</p>");
        }
        else if($("#mobile").val().length >= 1){
        $("#mobilesize").html("<p>"+data.validation[i].mobilesize+"</p>");
        }
      }

OTHER TIPS

Check your array structure:

var data = {validation:[
{"user":"user may not be empty"},
{"date":"Date may not be null"},
{"mobile":"passengerMobile may not be empty"},
{"mobileSize":"passengerMobile size must be greater than 11"},
{"name":"passengerName may not be empty"},
{"nameSize":"passengerName size must be between 2 and 30"},
 ]};

this is like (pseudo code):

data = object
data.validation = array
data.validation[0] = object
data.validation[0].user = "user may not be empty"
data.validation[1].user = undefined!!
data.validation[2].user = undefined!!
data.validation[3].user = undefined!!

So you have to change your structure..

For some of the values in the validation you do not have "user" hence you getting undefined.

Please use this code to avoid such issues:

if(typeof data.validation[i].user != "undefined" && data.validation[i].user){
    $("#username").html("<p>"+data.validation[i].user+"</p>");
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top