0

Currently on my project I have to trigger an ID whenever the window fully loads. So, to do that I have included jquery library and written the following script:

$(window).load(function(){
  $('#parent_cat').trigger('change');
});

But I would like to know how can I achieve the same with just javascript as using the entire jQuery library for just few lines of codes is not ideal. I did search on the internet for how to trigger change event when window loads with the help of javascript but the solutions didn't help. So, if any one can help me out.

A solution that I tried:

document.getElementById("parent_cat").onchange();

But did not work. It shows an error document.getElementById(...).change is not a function.

Kiran Dash
  • 4,816
  • 12
  • 53
  • 84

2 Answers2

1

Try .onchange() like this:

function onChange(elem) {
  alert(elem.value);
}
document.getElementById("parent_cat").onchange();
<select id="parent_cat" onchange="onChange(this)">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

Just add load event listener to window object:

window.addEventListener('load', function(){
    ... your code ...
});
nenadg
  • 420
  • 11
  • 16
  • Thanks, I was thinking that on load it would solve the issue but still it shows the error document.getElementById(...).change is not a function. – Kiran Dash Mar 01 '16 at 12:28