Skip to content
Advertisement

jQuery loop append result after every event

I apply each loop in jQuery with onchange() event.

        $(function() {
         $('#datatype').change(function(){
            $.getJSON('/background_process', {
            }, function(data) {
        var toAppend = '';
       $.each(data.result,function(i,o){
       toAppend += '<option >'+o+'</option>';
      });
               $("#result").append(toAppend);
            });
            return false;
          });
        });

<select name="datatype" id='datatype'>
        <option selected disabled >SELECT DATATYPE</option>
        <option value="RAW">RAW</option>
        <option value="DEPTH">DEPTH</option>
</select>
<select id=result name="result">
       <option value="NULL">SELECT TOKEN</option>
</select>

So my problem is when I select option(“RAW”) it return result as option values and then I select “DEPTH” option and it add “RAW” and “DEPTH” return result and give both data as option.

output – when I select “RAW”

<option>"raw-result"<option>
<option>"raw-result"<option>

When I select “DEPTH”

<option>"raw-data"<option>
<option>"raw-data"<option>
<option>"depth-data"<option>
<option>"depth-data"<option>

So I want, when I select option it return loop data and when again select option then it return new loop data not append data with previous select.

Output should like this- When I select “DEPTH” option after “RAW” option so it return

<option>"depth-data"<option>
<option>"depth-data"<option>

But it does not return that result.

Advertisement

Answer

You are appending the new data instead of replacing old one with it. Instead of append use html

$("#result").html(toAppend);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement