getJSON length in jQuery

2972 views javascript
1

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.

answered question

getJSON() returns a thenable/promise not the data retrieved from that url

2 Answers

8

$.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)
);

posted this
4

Solved.

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

posted this

Have an answer?

JD

Please login first before posting an answer.