1

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

user2742540
  • 45
  • 2
  • 7

3 Answers3

2

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>");
        }
      }
Siddique Mahsud
  • 1,453
  • 11
  • 21
  • 1
    ah..I don't Know how I missed that.Great! And I am Sorry for that I tried to vote But less reputation @Siddique Mahsud – user2742540 Feb 28 '14 at 06:31
1

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..

Hardy
  • 5,590
  • 2
  • 18
  • 27
0

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>");
 }
V31
  • 7,626
  • 3
  • 26
  • 44