How to delete a selectbox with Javascript one by one

Asked

Viewed 162 times

0

Hello... I have a button that by clicking the "addpergunta" button "clones" my selectbox which is like "Select the Question...". With each click it adds one more each time incrementing id to make it different. I wanted to do the opposite, like... by clicking the "cancel" id button delete the select’s one by one. I made the code below but it only leaves Hidden a select...

$(document).ready(function () {
    $('#cancelar').click(function () {
        var 
        $('#3').html('');  // Excluindo pelo id
        $('#3').hide();
    });
});

Javascript and HTML that adds the selectbox

$(document).ready(function () {
    var x = 1
    $('#addpergunta').click(function () {
        var itemCont = $("#itemCont").val();
        var novoItem = $("#1").clone();

        novoItem.attr("id", itemCont).attr("name", itemCont);

        $("#perguntas").append("<br />");
        $("#perguntas").append(novoItem);
        itemCont++;
        $("#itemCont").val(itemCont);
    });
});
<input type="hidden" id="itemCont" value="2" />
<div class="col-md-6" id="perguntas">
  <select class="form-control" name="1" id="1">
    <option value="0">Selecione a Pergunta...</option>
  </select>
</div>

<div class="form-group col-md-5">
  <div class="col-md-offset-4 col-md-9">
    <button type="submit" id="incluir" class="btn btn-default" style="height:35px; width:70px;">Incluir</button>
    <button type="button" id="addpergunta" class="btn btn-success" style="height:35px;" title="Adicionar Pergunta">
      <span class="glyphicon glyphicon-plus"></span>
    </button>
    <button type="button" id="cancelar" class="btn btn-danger" style="height:35px;" title="Cancelar">
      <span class="glyphicon glyphicon-ban-circle"></span>
    </button>
  </div>
</div>

2 answers

0


I decided by doing this...

var perguntaId = 0;
$(document).ready(function () {
    $('#addpergunta').click(function () { 
        var itemCont = $("#itemCont").val();
        var novoItem = $("#pergunta_1").clone();
        novoItem.attr("id", 'pergunta_' + itemCont);

        perguntaId = itemCont;

        $("#perguntas").append('<br />');
        $("#perguntas").append(novoItem);
        itemCont++;
        $("#itemCont").val(itemCont);
    });
});

$(document).ready(function () {
    $('#remover').click(function () {
        console.log(perguntaId);
        if (perguntaId > 1) {
            $('br').last().remove();
            $('#pergunta_' + perguntaId).remove();
            perguntaId--;
        }
    });
});

0

If you are able to get a list with each element "select" that you created, use the method $.fn.remove. This will remove each element (from the page) you have in an instantiated object from the jQuery class.

$("#perguntas select").remove();

That would do the same:

$("#perguntas select").each( 
/* novo estilo de função */
() =>
    /* statement único */
    this.parentNode.removeChild(this)
);

Explanation:

  • iterates each element of a jQuery object;
  • for each element, a removal of the HTML page.

Remembering: you will not lose reference to your elements when removing them, they will be removed only from the page. When an element (which is an object) is no longer used, the browser removes it automatically, it happens because of memory management (Garbage Collection).

So, let’s assume that we have a code where we have an HTML element stored in an object or variable:

var el = document.getElementById("id");

When removed from page,

el.parentNode.removeChild(el);

el will still be an HTML element (in modern browsers, all HTML elements would be objects, but in older browsers like MS Internet Explorer 6 an HTML element would be more native and could not get manipulation of methods, because the interface HTMLElement would not exist).

Edit: I forgot that you want to remove one by one element. This will depend on the order. If you want to remove the primary element you can use the method $.fn.first which will return the first element of your jQuery object, and that way you won’t need to know if the element exists since jQuery executes an action for each element you have in your pocket only if it exists (loop), then you can remove the elements(s) contained in the new object.

$("#perguntas select").first().remove();

Or, if you want to remove in the order below:

$("#perguntas select").last().remove();
  • Good explanation, but what I want is to remove a "select" each time you click the button.. and with these codes you passed removes everything inside the div.

  • @Marcoshenrique Then you need to capture the first "select" element of the jQuery object, check if it exists and finally remove it, or use the method $.fn.first to capture the first element. This will remove primary in primary.

  • @Marcoshenrique Editei

  • I did it differently... I created a variable and had it deleted while it was greater than 1 (My original select)... But I appreciate the help, gave a good clarity your explanation.

Browser other questions tagged

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