JavaScript good practices: remove inline onsubmit () global variables

I am learning good practices with JavaScript (by the way, if you have articles about this to recommend me, I will be grateful: D), and I have some questions about:

  • onsubmit(), onclick()and other built-in functions
  • What if a variable global
  • open() method

About 1 and 2

I have a form on my HTML page and I used this method:

<form name="myForm" onsubmit="myFunction();">

Inline JS is bad practice and I have to remove it. So, I deleted onsubmit="myFunction();"and added to my JS (to an external file):

var form = document.myForm;

form.onsubmit = function myFunction() { /* codes hidden here */ };

But...

1. Why is my code not working? Should I use window.onloadbefore? Sometimes I donโ€™t know when I should use it.

2. , (, form ). ?

3

3. URL-, , . , open() . ? , ?

+3
3

:

var form = document.myForm;

DOM, form undefined. , , , .

, DOM, DOM. , body.

, DOMReady ( ) , , script.

form.onsubmit = function myFunction() { /* codes hidden here */ };

undefined ...: - (

, ( , , , IE), - :

var formElement = document.forms['myForm'];

, , ( , ). :

window.onload = function() {
  var form = document.myForm;
  form.onsubmit = function myFunction() { /* codes hidden here */ };
}

, . - .

+1

window.onload , . - , :

(function(){
  var form = document.myForm;
  form.onsubmit = function myFunction() { /* codes hidden here */ };
})();

3 , URL-? :

<a href="http://www.myurl.com" target="_blank">Click on my url</a>

target=_blank URL , .

+1
  • , :

    var form = document.getElementById("form");
    form.addEventListener("submit", function(e) {
    e.preventDefault();
    console.log('form has been submitted!');
    });
    

    , , , DOM, ( RobG).

  • You should declare the main object, for example app, and then add everything you need as its properties or functions:

    var app = {};
    app.formElement = document.getElementById("form");
    app.submitButton = document.getElementById("submitBtn");
    app.someFunction = function(number){ return number};
    

    Keep in mind that you can also add objects to this object for further categorization.

  • .open() the method is considered bad practice from a UX point of view because it just opens a popup.

+1
source

All Articles