简体   繁体   中英

Why doesn't the form entry update after button click [JS]?

I am writing a little script which should do the following actions:

1) a button click triggers a form to load.

2) an entry of the form is filled with a specific value.

My code looks something like this:

document.getElementById('formButton').click();
window.onload = function(){
  document.getElementById('formEntry').value = "foo";
};

This script loads the form,but the form entry doesn't update. I suppose that the problem is that the form entry hasn't loaded in the DOM yet, but onload doesn't seem to do the job... Any hints on what I'm doing wrong here?

You should bind the button click to an event listener:

window.onload = function(){
  document.getElementById('formButton').addEventListener('click',function(){
    document.getElementById('formEntry').value = "foo";
  });
};

By calling the .click() function you just trigger any given click event listeners, but you haven't declared one, and thats also propably not your intention.

Do this -

1) You have to put all of the document variables inside window.onload

window.onload = function() {
  var formEntry = document.getElementById('formEntry');
  var formButton = document.getElementById('formButton');
};

2) You have to change the formEntry when the formButton is clicked, so put the .value change inside another function like so

window.onload = function() {
  var formEntry = document.getElementById('formEntry');
  var formButton = document.getElementById('formButton');

  formButton.addEventListener('click', function() {
    formEntry.value = "foo";
  });
};

or alternatively

window.onload = function() {
  document.getElementById('formButton').addEventListener('click', function() {
    document.getElementById('formEntry').value = "foo";
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM