defff_metal
defff_metal

Reputation: 1

Resetting div contents using Jquery

I'm having trouble figuring out how to reset the content of a div with a button using Jquery. Currently, when .button is pressed I get a random letter all three of divs. So far so good, however, when pressing it again, the first letter stays and another letter is added. I need the first result to go away and for a new letter to display. Here is my code..

$(document).ready(function() {
  $('.button').click(function() {
    var itemList = new Array("A", "B", "C", "D", "E");
    var randomItem = Math.floor(Math.random() * (itemList.length));
    $('.random1').append(itemList[randomItem]);
    var randomItem = Math.floor(Math.random() * (itemList.length));
    $('.random2').append(itemList[randomItem]);
    var randomItem = Math.floor(Math.random() * (itemList.length));
    $('.random3').append(itemList[randomItem]);
  });
 $('.reset').on('click', function(){
    $(".random1").trigger("reset");
  });
});

Upvotes: 0

Views: 92

Answers (2)

Wesley Smith
Wesley Smith

Reputation: 19571

Spencer got you sorted but I would also mention that in addition to using .text() instead of .append() to fix your main issue, you could also simplify your code a good deal by using .each() like this:

$(function() {
  $('.button').click(function() {
    var itemList = ["A", "B", "C", "D", "E"];
    $('.random').each(function(){
        $(this).text(Math.floor(Math.random() * (itemList.length)));
    });
  });
 $('.reset').click(function(){
    $(".random").text("");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Get random</button><button class="reset">reset</button><br><br>
<div class="random"></div><br>
<div class="random"></div><br>
<div class="random"></div><br>
<div class="random"></div><br>

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

This is because you are using the .append(val) method, which will append the new data to the old data at the end of the element. If you would like the old data inside the element to be cleared, then use the .text(val) method.

For example you would change this line:

$('.random1').append(itemList[randomItem]);

To:

$('.random1').text(itemList[randomItem]);

Upvotes: 1

Related Questions