Javascript remove() does not work

Asked

Viewed 154 times

0

See the script below. Why remove() doesn’t work? I recently posted on this link: post something similar, but in the other case, the problem was why the button was inside a form, but this time there is no form on the page I already changed to input <a href="#"></a> button, but nothing works!

        function buscar(tamanho){
        var pasta = $('#pasta').val();  
        // utilizando o split para quebrar o diretorio e receber somente o nome da pasta
        var dirimg = pasta.split("/galeriaimg/");
        $.ajax({
            url: 'galeria.php?pasta=' + dirimg[1] + '&tamanho=' + tamanho,
            dataType: 'json',  

                success: function(result){ 

                   $.each(result, function(key, value){
                        var container = '<div class="col-md-4 id="col-'+key+'">';
                        container +=        '<div class="img-wrap">';
                        container +=            '<img src="/wpauditoria/images/'+tamanho+'/galeriaimg/'+dirimg[1]+'/'+value+'" class="img-return" alt="galeria" "/>';    
                        container +=            '<a href="#" class="btn btn-default btn-sm delete" onclick="excluir('+key+')"><i class="fa fa-trash"></i></a>'; 
                        container +=         '</div>';    

                        container +=         '<input type="hidden" name="imagemgaleria['+key+'][titulo]" value="/galeriaimg/'+dirimg[1]+'/'+value+'" />';    
                        container +=         '<input type="text" placeholder="Título" name="imagemgaleria['+key+'][titulo]" class="form-control inputgaleria" />';   
                        container +=         '<input type="text" placeholder="Link" name="imagemgaleria['+key+'][link]" class="form-control inputgaleria" />';   
                        container +=         '<textarea name="imagemgaleria['+key+'][descricao]" placeholder="Descricao" class="form-control inputgaleria" ></textarea>';   
                        container +=    '</div>';   

                        $('#galeriaimg').append(container);
                   });
             }
        });
    }

    function excluir(id){  
        console.log(id);  
        $("#col-"+id).remove();
}

I performed a console.log(id) to see if the id was being passed and this part works normally, the function receives the ID but does not execute the instruction $("#col-"+id).remove(); and also does not return error message.

Html

<body>

<!-- FORMULARIO HTML CADASTRO DE IMAGEMS -->
<div class="panel panel-primary panel-horizontal" style="margin-top: -19px;">
    <!-- div responsavel pela borda lateral.. e pelo conteudo se houver... -->
    <div class="panel-heading "></div>
    <div class="panel-body ">
        <!-- Container fluido para ajustar automaticamente o layout --> 
        <main role="main" class="container">
          <!-- Page Header -->
          <div class="page-header">
            <h2><a id="content">Inclusão de Galeria de Imagens no Site</a></h2>
            <div>Inclua uma Galeria para realizar uma transição de fotos para os seus usuários.</div>
          </div>

          <!-- tab da pagina -->
          <ul class="nav nav-tabs">
            <li class="active"><a href="#">Inclusao de Imagens</a></li>
          </ul>

          <!-- Classe Responsavel pelo tamanho e por centralizar do Panel -->
          <div class="col-sm-8 col-md-offset-2"> 

          <!-- Div responsavel pelo titulo em azul do form -->  
          <div class="page-header">
          <!-- Div responsavel por alinhar os panels  -->  
          <div class="panel-group">
            <div class="panel panel-primary">
              <div class="panel-heading">
                  <div class="panel-title text-center">Cadastro de Imagens</div>
                </div> 
              </div>

                <!-- div responsavel pelo panel lateral na horizontal -->
                <div class="panel panel-primary panel-horizontal">
                  <!-- div responsavel pela borda lateral.. e pelo conteudo se houver... -->
                  <div class="panel-heading"></div>
                    <!-- Classe Responsavel pelo conteudo do panel-->
                    <div class="panel-body">

                          <!-- Titulo-->
                          <div class="panel panel-primary">
                            <div class="panel-body">     
                                <div class="col-xs-5  col-md-7">
                                      <label for="titulo">Título:</label>
                                      <!-- Campo Pasta e Seleção de Imagens-->
                                      <div class="input-group text-center">
                                          <input type="text" placeholder="Título" name="titulo" id="titulo" class="form-control " value="">   
                                      </div> 
                                </div>      

                                <div class="col-xs-5  col-md-4">
                                      <label for="pasta">Pasta:</label>
                                      <!-- Campo Pasta e Seleção de Imagens-->
                                      <div class="input-group">
                                          <span clas="input-group-btn text-center">
                                            <a href=<?=(Empty($dir))?"/assets/libs/filemanager/dialog.php?type=2&field_id=pasta": "/".$dir."/assets/libs/filemanager/dialog.php?type=2?&field_id=pasta"?> class="btn btn-info fancy" data-fancybox-type="iframe">
                                                <i class="fa fa-folder-open-o"></i>
                                            </a>
                                          </span>                                     
                                          <input type="text" placeholder="Pasta" class="form-control" name="pasta" id="pasta" onchange="buscar('medium')" value="">   
                                      </div>                                         
                                </div> 


                                <!-- Div Responsável por exibir o conteudo da galeria de imagens -->   
                                <div class="row">
                                    <div id="galeriaimg">                        
                                    </div>
                                </div>


                                <?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'; 
                                    }
                                ?>

                                <div class="text-center">
                                   <input type="button" value="Limpar Imagem" onclick="clearimg('<?=$img_padrao?>')" class="btn btn-danger text-center oculto">             
                                </div>
                               </div>    

                            </div>                            
                    </div> <!-- Panel body -->
                </div> <!-- Panel horizontal -->

                    <!-- Campo Botão Cadastrar --> 

                    <div class="panel panel-primary panel-horizontal">
                      <!-- div responsavel pela borda lateral.. e pelo conteudo se houver... -->
                      <div class="panel-heading "></div>
                        <div class="panel-body ">
                            <button type="Submit" name="cadastrar" id="cadastrar" value="cadastrar" onclick="window.onbeforeunload = null;" class="btn btn-primary center-block oculto">Cadastrar</button>
                        </div>
                      </div>   





                <!-- Botao de Paginacao -->           
                <ul class="pager">
                  <li class="previous col"><a href="galeriaimg.php">Voltar</a></li>
                </ul>
              </div>

    </div>
    </div><!-- panel group -->
    </div> <!-- pagheader -->
    </div><!-- /.col-sm-8 -->

Alert print confirming receipt of ID

inserir a descrição da imagem aqui

Console Element Print, Id is also passed! inserir a descrição da imagem aqui

  • Put the HTML you are using there.

  • where you ta calling the delete function?

  • @haykou no href that has in the code

  • @Davidsamm , html posted, abs

  • Ixi! I saw nothing calling the function excluir().

  • @Davidsamm calling in the code of the ajax, in that part container += '<a href="#" class="btn btn-default btn-sm delete" onclick="excluir('+key+')"><i class="fa fa-trash"></i></a>';

  • Ah tah rs.. had not seen

  • @Diegolela and its seeking function is working?

  • @haykou is yes! displays the pictures only delete button that doesn’t work! complementing, it even works displays the id, but the part where the remove() is not clearing the div

  • See if on the console a '<div class="col-md-4 id="col-'+key+'">'; is passing the value key correctly in this div.

  • @Diegolela and where is the div with id col ?

  • Let’s assume that this key be "10", see if on the console the created div appears '<div class="col-md-4 id="col-10">';. It may be going empty, there the function excluir() not finding anything.

  • Boot one console.log(key) below the line $.each(result, function(key, value){ to see if this value key is passing correctly.

Show 8 more comments

3 answers

2


A suggestion also to make your code cleaner:

And instead of you concatenating the lines repeating the variable container, just put a + at the beginning of each line, and only place ; at the end of the last.

Instead of:

var container = '<div class="col-md-4" id="col-'+key+'">';
container +=        '<div class="img-wrap">';

Use:

var container = '<div class="col-md-4" id="col-'+key+'">'
+'<div class="img-wrap">'
....
+'</div>';
  • thanks for the tip! these details are very valuable for those who are in the beginning! =]

2

Thanks for the help @haykou and @Davidsamm

The problem was in the following excerpt

<div class="col-md-4" id="col-'+key+'">';

was missing a double quotes at the end of the "col-md-4"why the instruction did not work!

0

From what I’ve seen your code is correct but missing the correct element in the remove, follows an example of what you are doing below:

<div id="app">
 <div class="teste"></div>
 <div id="col-1">hello</div>
</div>

js

 function buscar(){
      var teste = '<a onclick="excluir(1)">ok</a>';
   $('#app').append(teste);
 }

    function excluir(id){  
       alert('ok');
      $('#col-'+id).remove();
}

buscar(1);

By clicking on to, it performs the delete function normally.

  • That doesn’t answer the question. You just posted a simple example that works by disregarding his code. As he said in the question, the code is going correctly to the function excluir(). The problem must be in the code inside Ajax when it creates the element dynamically.

  • @Davidsamm to update the post with an Alert and console 1 minute

  • @Davidsamm you found the element with id = col ?

  • Yes, inside the Ajax: var container = '<div class="col-md-4 id="col-'+key+'">';

  • @Davidsamm by print seems to have a space between the quotes and the col...

  • but my code doesn’t have that space! =/

  • Thank you guys it was mistake right there! missing a double quotes"

  • That’s right! Double quotes after col-Md-4.

Show 3 more comments

Browser other questions tagged

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