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.

0

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Just add load event listener to window object:

window.addEventListener('load', function(){
    ... your code ...
});

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.