0

I have a js file:

I am trying to read the value f a dropdown list which has an ID = "topn". When I do that at POS1 it gives an error :

Cannot read property 'options' of null

At POS2 it works fine. But I want the value at POS1. Where have I gone wrong??. I am using latest version of Google Chrome.

window.onload = getAll();

function getAll() {
  var data = new FormData();
  //console.log(document.location.href);

  /* POS1 */
  var test = document.getElementById("topn");
  console.log(test.options[test.selectedIndex].value);
  /**/

  data.append('top_n', test.options[test.selectedIndex].value);
  data.append('top_n', 5);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://xyz.php', true);
  xhr.onload = function() {
    console.log("done here");
    var table_dom = document.getElementById("tab1");
    /* POS2 */
    var test = document.getElementById("topn");
    console.log(test.options[test.selectedIndex].value);
    /**/
    response_text = this.responseText;
    response_text.replace(/['"]+/g, '');
    console.log(response_text);
    table_dom.innerHTML = response_text;
  };
  xhr.send(data);
}
mplungjan
  • 134,906
  • 25
  • 152
  • 209
Jijo
  • 1,024
  • 3
  • 12
  • 20
  • 1
    Why are you defining the variable twice? The variable `test` is accessible inside the `xhr.onload` function. Just use that. – evolutionxbox Jul 13 '16 at 14:28
  • 2
    `window.onload=getAll;` If getAll returned a function you could use your syntax but it does not so you are replacing the onload handler with your function. – mplungjan Jul 13 '16 at 14:29
  • 4
    Duplicate of http://stackoverflow.com/questions/4842590/run-function-when-page-is-loaded – mplungjan Jul 13 '16 at 14:34

0 Answers0