user745235
user745235

Reputation:

JQuery - Clean Select options on new request

I have a SELECT object and I'm populating it with AJAX(JQUERY).

$("#setor").change(function(){
    $("#loading").css("display", "inline-block");
    $.ajax({
        type: "POST",
        url: "<?php echo base_url();?>quadracontroller/lista_quadras/"+$("#setor").val(),
        success: function(html) {
            $("#quadra").append(html);
            $("#loading").css("display", "none");
        }
    });
});

HTML

<select name="quadra" id="quadra">
                                    <option value="0" selected="selected">--</option>
                                </select>

The thing is that for each request it is incrementing the options on the select.

How do I do to clean the generated on the previous request?

Thanks in advance and sorry for my poor English =)

Upvotes: 0

Views: 11181

Answers (4)

Jordan Running
Jordan Running

Reputation: 106027

I would save the initial state upon page load(1) and then restore it before doing .append(). Like this:

// save the initial HTML
$('#quadra').data('initial-options', $('#quadra').innerHTML);

$("#setor").change(function(){
  $("#loading").css("display", "inline-block");
  $.ajax({
    type: "POST",
    url: "<?php echo base_url();?>quadracontroller/lista_quadras/"+$("#setor").val(),
    success: function(html) {
      var quadra = $("#quadra");

      // restore the initial HTML
      quadra.innerHTML = $('#quadra').data('initial-options');
      quadra.append(html);

      $("#loading").css("display", "none");
    }
  });
});

Upvotes: 1

Briguy37
Briguy37

Reputation: 8402

$('#quadra').find('option').remove();

Here's a fiddle for a demo.

Upvotes: 2

Jishnu A P
Jishnu A P

Reputation: 14382

Try this

 $("#quadra").html(html);

Upvotes: 1

ek_ny
ek_ny

Reputation: 10243

   $("#quadra").empty();
   $("#quadra").append(html);

Upvotes: 7

Related Questions