Doubt - Function to clear img with javascript does not work

1

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

I looked at the browser console and there was no error message ... Can you tell me where I'm wrong?

Here is 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 is 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);
}
    
asked by anonymous 23.08.2017 / 23:42

1 answer

3

Your button tag is probably performing its default action, in addition to the onclick event, which is probably the submit on a form. To avoid this, you can specify the button type:

<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, such as <input type="button"> or <a href="javascript:void(0);"></a> .

    
24.08.2017 / 00:04