1

I'm writing a JS file that deals with the client events in an HTMl page. Register form is one of these events ,so the user inserts his name and password and when clicking the submit button ,JS file must deal with this event.

var registerForm = document.getElementsByClassName('register-form');
registerForm[0].addEventListener('submit',function(e) {
      var username = document.getElementsByClassName('register-form-username')[0].value;
      var userpass = document.getElementsByClassName('register-form-pass')[0].value;
      var userDetails={
          name : username,
          pass: userpass
      };

      console.log(JSON.stringify(userDetails)); /*this is working and it print out on the console the same name and pass the user entered*/
      globalvar.register(userDetails);

    });

var globalvar= {
    register : function(userDetails) {   
        console.log(JSON.stringify(userDetails));  //this does not print in the console and it refreshes the page and reset the form fields 
        var x={
            comment : "", 
            userDetails: {
                name : userDetails.name , 
                email : userDetails.pass
            }
        };
        console.log(JSON.stringify(x));
        localStorage.setItem('localStor' , JSON.stringify(x));
    }
};

what am I missing?

Dekel
  • 60,707
  • 10
  • 101
  • 129
user8244016
  • 929
  • 3
  • 12
  • 24

3 Answers3

4

If you want to disable the default behavior of the submit (which cause the page to refresh) you will need to use the preventDefault() method of the Event object:

registerForm[0].addEventListener('submit',function(e) {
    e.preventDefault()
    ...
});
Dekel
  • 60,707
  • 10
  • 101
  • 129
0

It's because the event is fired and it's subtmiting the form, to prevent it you can in the first line:

e.preventDefault()

Sergio Escudero
  • 1,798
  • 14
  • 21
0

You can either stop your form from submitting and reloading the page which causes you to lose the console information, or in Chrome choose to preserve the log, which will retain the log between any reloads.

To preserver the console in Chrome, click the gear icon in the console's upper right corner and choose "Preserve log". Then you can run your script as-is.

j08691
  • 204,283
  • 31
  • 260
  • 272