Evan Butler
Evan Butler

Reputation: 667

How do I reset the list after each input?

This is the Ping Pong Test. Every time I click the Start button and enter a number it just adds to the list. How do I get it to reset the list after every input?

$(document).ready(function() {
    $("#Start").click(function() {
        var number = parseInt(prompt("Please pick an integer to play."));

        for(index = 1; index <= number; index +=1) {
            if (index % 15 === 0) {
                $('#list').append("<li>" + "ping-pong" + "</li>");
            } else if (index % 3 === 0) {
                $("#list").append("<li>" + "ping" + "</li>");
            } else if (index % 5 === 0 ) {
                $("#list").append("<li>" + "pong" + "</li>");
            } else {
                $("#list").append("<li>" + index + "</li>");
            }
        }
    });
});

Upvotes: 0

Views: 215

Answers (3)

Deepak
Deepak

Reputation: 51

Instead of doing .append, do .html()

.append adds a new child element, but .html() clears all its children and makes the new element you add as its child.

Try out:

$(document).ready(function() {
    $("#Start").click(function() {
        var number = parseInt(prompt("Please pick an integer to play."));

        for(index = 1; index <= number; index +=1) {
            if (index % 15 === 0) {
                $('#list').html("<li>" + "ping-pong" + "</li>");
            } else if (index % 3 === 0) {
                $("#list").html("<li>" + "ping" + "</li>");
            } else if (index % 5 === 0 ) {
                $("#list").html("<li>" + "pong" + "</li>");
            } else {
                $("#list").html("<li>" + index + "</li>");
            }
        }
    });
});

Upvotes: 1

Carsten
Carsten

Reputation: 18446

To reset (empty) your list, use

$('#list').empty();

Upvotes: 2

Travis J
Travis J

Reputation: 82287

Before you prompt, remove the li elements from #list

$("#Start").click(function() {
    $("#list li").remove();
    var number = parseInt(prompt("Please pick an integer to play."));

Upvotes: 1

Related Questions