php - Select boxes auto populated by JSON sometimes need a refresh before displaying -
i have json file being used autopopulate select boxes. every , (i can't recreate fault, appears random) items in drop down not display until refresh page.
i've checked console , log etc, file loading fine, no errors appearing , i'm little @ loss.
any ideas?
example of json , script reads below.
thanks.
"radabsorbed" : [ { "value" : "rad", "name" : "rad(rd)" }, { "value" : "millirad", "name" : "millirad(mrd)" }]
and script:
<script> // json: // key class identifier, temp, area etc etc // value being used both id , value when list being populated $.getjson('json/conversionjson.json', function(data){ console.log(data); //for testing output var list = $("<ul />"); $.each(data, function (key, conversions) { console.log(key + ":" + conversions); $.each(conversions, function (index, conversion) { console.log("<li>name: " + conversion.name + " :value: " + conversion.value + "</li>"); if(key == "<?php echo $conversiontype ?>"){ $("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>'); //testing output var elem = $("<li>name: " + conversion.name + " :value: " + conversion.value + "</li>").appendto(list); } }); }); //$("#testjson").html(list); }); </script>
edit: updated script.
$(document).ready(function(){ $.getjson('json/conversionjson.json', function(data){ console.log(data); //for testing output var list = $("<ul />"); $.each(data, function (key, conversions) { console.log(key + ":" + conversions); $.each(conversions, function (index, conversion) { console.log("<li>name: " + conversion.name + " :value: " + conversion.value + "</li>"); if(key == "<?php echo $conversiontype ?>"){ $("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>'); $("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>'); //testing output var elem = $("<li>name: " + conversion.name + " :value: " + conversion.value + "</li>").appendto(list); } }); }); //$("#testjson").html(list); }); });
edit: help, seems working fine , looked amateur mistake on part.
i think problem script running before document ready.
try wrapping code in document ready function:
$(function() { $.getjson(...) // ... });
this make code doesn't execute before elements it's affecting created. instance, if code executes before element id from
gets created, $('#from')
not match elements, , won't work.
wrapping in document ready function make sure code waits until elements have been created before executing.
alternatively, move <script>
tag out of head , place right after #from
element in html. might load faster.
Comments
Post a Comment