How to make a button type "button" perform a javascript function instead of performing Submit

Asked

Viewed 580 times

0

I have more than one Button inside the form. And I need one of them to perform a javascript function while the other performs Submit. But it turns out the two of them are performing Ubmit, and I need the button to be in the form. The "Confirm" button performs Ubmit and the other should perform the eye function(), but it tbm ta working as Ubmit, even if it is of type button. Then I would have to prevent the event Ubmit and perform the eye function(), but I can’t do it. I thank you already.

function olho() {
    if (document.getElementById('senha').type == 'password') {
        document.getElementById('senha').type = 'text';
        var img = document.getElementById('img-olho');
        img.src = 'img/olho-fechado.svg';
    } else {
        document.getElementById('senha').type = 'password';
        var img = document.getElementById('img-olho');
        img.src = 'img/olho-aberto.svg';
    }   
}
<form id="form" method="POST" action="#">
		<label id="label-user">Usuário:</label>
			<input type="text" name="usuario" id="usuario" placeholder="Digite seu email..."><br>
		<label id="label-senha">Senha:</label>
			<input type="password" name="senha" id="senha" placeholder="Digite a senha...">
			<button type="button" onclick="olho()" id="olho"><img id="img-olho" src="img/olho-aberto.svg"/></button>
		<button type="submit" id="botao">Confirmar</button>
</form>

1 answer

0


So if the button’s not the type Submit there is no reason why the form should be sent, as you can see in the example. If you click the button with the image the form is not submitted and performs the function I advise you to change name, because there may be problems with the button id:

function olhos() {
  if (document.getElementById('senha').type == 'password') {
    document.getElementById('senha').type = 'text';
    var img = document.getElementById('img-olho');
    img.src = 'img/olho-fechado.svg';
    console.log('Não enviou');
  } else {
    document.getElementById('senha').type = 'password';
    var img = document.getElementById('img-olho');
    img.src = 'img/olho-aberto.svg';
  }
}
<form id="form" method="POST" action="#">
  <label id="label-user">Usuário:</label>
  <input type="text" name="usuario" id="usuario" placeholder="Digite seu email..."><br>
  <label id="label-senha">Senha:</label>
  <input type="password" name="senha" id="senha" placeholder="Digite a senha...">
  <button type="button" onclick="olhos()" id="olho"><img id="img-olho" src="img/olho-aberto.svg"/></button>
  <button type="submit" id="botao">Confirmar</button>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.