Pryda
Pryda

Reputation: 1029

getJSON length in jQuery

I want to set an input value to the length of JSON file

HTML:

<input type="text" class="form-control" placeholder="" id="myInput">

jQuery:

$('#myInput').val(($.getJSON("myJSON.json").length+1).toString());

I receive NaN always.

Upvotes: 0

Views: 187

Answers (2)

Pryda
Pryda

Reputation: 1029

Solved.

$.getJSON("myJSON.json", function(data){
    $('#myInput').val(data.length);
});

Upvotes: 0

laruiss
laruiss

Reputation: 3816

$.getJSON is asynchronous, and no need to invoke the toString() method. The data received is not necessarily a string (it is not the JSON, but the parsed JSON).

$.getJSON("myJSON.json").then(data =>
  $('#myInput').val(data.length + 1)
);

Upvotes: 1

Related Questions