Doubt - Clear img function with javascript does not work

Asked

Viewed 210 times

1

I need to clear a field img and for this I am using the code below, but by clicking on button javascript does not work because the page receives a refresh.

I have scanned the browser console and no error message appears... Can you tell me where I am missing??

Here’s the button code

   <?php
// verificando o diretorio utilizado para fins de desenvolvimento 
  diretorio();
  if(Empty($dir)){
    $img_padrao = '/images/sem_imagem.jpeg';
  }else{
    $img_padrao = '/'.$dir.'/images/sem_imagem.jpeg'; 
    }
  ?>                                  
  <img src='<?=$img_padrao?>' class='img-thumbnail limpar' id="img" alt="Img Destaque">                                


  <button id="apagar" onclick="clearimg('<?=$img_padrao?>')" class="btn btn-danger tabindex='4'">Remover Imagem</button>    

here the javascript

// função responsavel por apagar a imagem do Box (exibir a imagem padrão).
function clearimg($img_padrao){
var clearimg = $img_padrao; 
$('.limpar').attr('src', clearimg);
}
  • 1

    Is that button inside some form? It has to be the button tag?

  • is inside a form yes, and does not need to be the tag button

  • you killed my problem! I switched to input and it worked... lack of experience disturbs and too.. Thank you! hugs!

1 answer

3


Probably your tag button is performing her default action in addition to the event onclick, which is probably the Submit in a form. To avoid this, you can specify the type of button:

<button type="button">Botão</button>

Or you can avoid the default action by returning false in the event function:

function acao() {
    return false;
}

Or use another tag, like a <input type="button"> or <a href="javascript:void(0);"></a>.

Browser other questions tagged

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