简体   繁体   中英

Onclick html call for JavaScript function not working in Safari

I am trying to call a function in my javascript file from an onclick event in html. This code works perfectly in Google Chrome but does not work in Safari as it redirects to the same page and empties the form, without redirecting to the home page of my website.

Here is my HTML code:

<!-- Login or subscribe form-->
  <div class="py-5">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="card text-white p-5 bg-primary signUpBoxStyle">
            <div class="card-body">
              <h1 class="mb-4">Effettua il login o iscriviti</h1>
              <form>
                <div class="form-group"> <label>Indirizzo email</label>
                  <input type="email" class="form-control" placeholder="Inserisci email" id="email"> </div>
                <div class="form-group"> <label>Password</label>
                  <input type="password" class="form-control" placeholder="Password" id="password"> </div>
                <input type="button" class="btn btn-light text-primary btn-sm" value="Accedi" onclick="loginFunction()">
                <input type="button" class="btn btn-light text-primary btn-sm" value="Crea un Account" onclick="signupFunction()">                      </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

And this is my JavaScript

function loginFunction() {
  let email = document.getElementById('email').value;
  let password = document.getElementById('password').value;
  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;
  })
};

You might need to tell the browser not to carry out the default behavior of that element via preventDefault() . This SO answer give a little more detail.

Having an if statement to check the attribute is not that scalable but it may be possible that you pass the function call as a parameter.

 let buttons = document.querySelectorAll('input[type=button]') buttons.forEach(button => { button.addEventListener('click', e => { let func = e.target.getAttribute('data-call') if (func === 'login') { loginFunction() } else if (func === 'signup') { signupFunction() } }) }) let loginFunction = () => { console.log('loginFunction') } let signupFunction = () => { console.log('signupFunction') } 
 <form> <input type="button" value="Accedi" data-call="login"> <input type="button" value="Crea un Account" data-call="signup"> </form> 

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