简体   繁体   中英

Unobtrusive Javascript on a Submit Button

I'm trying to write an unobtrusive function on a submit button without the use of jQuery and the like. I have the following bit of code in my HTML form:

document.getElementById('help_submit').onclick = function (){
    window.alert("You clicked on the Submit Button on the Help Request form.");
};

And I'm trying to use on the following HTML button:

<input type="submit" id="help_submit" value="Submit Help Request" />

However when I try to fire the event, the form doesn't pop up with the Message Box and submits anyway.

I check the developer tools in Chrome and I see the following error:

Uncaught TypeError: Cannot set property 'onclick' of null

Where did I go wrong with the coding?

It seems likely that you are running your Javascript too early before the DOM has loaded and thus document.getElementById('help_submit') does not find the DOM element because it is not yet in the page. You can fix this by moving the script that contains this code to right before the </body> tag so all DOM elements will be present when the script runs. For more details on this issue, consult this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it .

In addition, your submit handling code needs to prevent the default action of the submit button or the form will submit anyway. Though, if you don't want the form to submit, then you should just stop using a submit button and use a regular button.

In addition to moving the script to the end of the DOM, I'd suggest you change your event handling code to this:

document.getElementById('help_submit').addEventListener('click', function (e) {
    e.preventDefault();
    window.alert("You clicked on the Submit Button on the Help Request form.");
});

Working demo: http://jsfiddle.net/jfriend00/vcjtv0kz/

I'm not experienced in JavaScript, but, following on the comment and the answer already given, try changing your code the following way:

  1. Remove the given code (it will be used differently at the next steps).

  2. Inside the script tag inside the head element, try creating two functions called, say, initialization and message:

     function initialization() { element = document.getElementById('help_submit'); element.addEventListener( 'click', message, false ); } function message() { window.alert("You clicked on the Submit Button on the Help Request form."); } 
  3. At the end of this script tag, write the following:

     window.addEventListener( "load", initialization, false ); 

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