Faisal Faisal - 3 months ago 9
HTML Question

onchange didn't work inside my function that render json parse

I have this code from w3school and modified it to suit my need and I come up with this code

<div id="city"></div>
<p id="demo"></p>
<div id="province"></div>
<script>
(function () {
var xmlhttp = new XMLHttpRequest();
var url = "http://getpark.net/city/read";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<div class='row'>" +
"<div class='large-12 columns'>" +
"<label>City</label>" +
"<select id='select' name='city' onchange='change()'>";

for(i = 0; i < arr.length; i++) {
out += "<option value='" +
arr[i].cityId +
"'>" +
arr[i].cityName +
"</option>";
}
out += "</select>" +
"</div>" +
"</div>";
document.getElementById("city").innerHTML = out;
}

function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}

})();


but why that onchange in change() function didn't work out? I see it from w3school.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange
thank you.

Answer

Your change-function should be in the global scope. You only have to move the declaration of the function directly after the script-tag.

<script>
function change() {
  var x = document.getElementById("select").value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
(function () {
[..]
Comments