How do I clear a list in Javascript?

Asked

Viewed 445 times

3

This is my HTML list;

 <div class="form-group">
     <label class="col-sm-2 control-label"><fmt:message key="label.sagresPessoal.tela.prestacao.unidade.jurisdicionada" /></label>
     <div class="col-sm-8">
         <select id="idUJ" name="prestacaoFolha.idUnidadeGestora" class="form-control select2 ">
             <option value ="">-</option>
             <c:forEach items="${listPessoaJuridica}" var="PJ">
                 <option value="${fn:replace(PJ.codigo,'.','')}">${PJ.nome}</option>
             </c:forEach>
         </select>
     </div>
 </div>

I can empty the other fields like this;

$('#idPeriodoInicio').val("");
    $('#idMotivo').val("");
    $('#idPeriodoFim').val("");

But I didn’t have the same success with the list, I tried that way;

$('#idUJ option').each(function(index) {
    if (index !== 0) {
        $('#idUJ').val().splice(0,$('#idUJ').val().length);
    }
});

How should I do?

2 answers

2

Using Jquery, you can do it this way:

<script
  src="https://code.jquery.com/jquery-3.4.0.slim.min.js"
  integrity="sha256-ZaXnYkHGqIhqTbJ6MB4l9Frs/r7U4jlx7ir8PJYBqbI="
  crossorigin="anonymous"></script>
  
<select id="droplist">
	<option>Opção 1</option>
	<option>Opção 2</option>
	<option>Opção 3</option>
	<option>Opção 4</option>
</select>

<input type="button" value="Apagar Opções" onclick="Apagar()">

<script type="text/javascript">
	function Apagar(){
		$("#droplist").empty();
	}
</script>

  • Nice and compact. But by the example in the question he wants you to keep the first item. It would be something like $("#idUJ").empty().append('<option value="">-</option>'); (Little world huh, Bins? P)

  • Really the world is very small :-) Considering what you said, this is how you commented.

1


Try this:

$('#idUJ')
    .find('option')
    .remove()
    .end()
    .append('<option value="">-</option>');

EDIT

Or a cleaner way, suggested by @Sam in the comments:

$('#idUJ').html('<option value="">-</option>');
  • 1

    Pq use 4 methods if only 1 can be used: $('#idUJ').html('<option value="">-</option>');? :)

Browser other questions tagged

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