Is there a way to clear the list after each input is made?

Looking for help with the Ping Pong Test. Whenever I click Start and enter a number, it just keeps adding to the list. How can I make it reset the list after each 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>");
                }
            }
        });
    });

Answer №1

If you need to clear your list and start fresh, follow this step:

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

Answer №2

Prior to asking for input, ensure that the li tags are deleted from the #list

$("#Start").click(function() {
    $("#list li").remove();
    var num = parseInt(prompt("Select an integer to begin playing."));

Answer №3

Why not use .html() instead of .append?

While .append adds a new child element, using .html() will clear all existing children and set the new element as its child.

Give this a try:

$(document).ready(function() {
    $("#Start").click(function() {
        var number = parseInt(prompt("Please choose 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>");
            }
        }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

Steps for preventing a button from being enabled until all mandatory fields are completed

Is it possible to have a button disabled until all required fields are filled out, with the button appearing grey in a disabled state and changing color when all fields are completed? I am facing an issue where clicking on the previous button is causing ...

Problem with sending variable via AJAX

Hey everyone, I'm attempting to send form data along with an extra variable using AJAX. Here's the code snippet: function tempFunction(obj) { var data = $('form').serializeArray(); data.push( { no: $(obj).at ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

What is the process for displaying all cookies in node.js?

I recently wrote some node.js code to retrieve cookies for a specific route. router.get('/', function (req, res, next) { var cookies = req.cookies; res.render('cartoons', { Cookies: cookies, }); }); In my cartoons Jade file, the ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

Following a POST request, the redirection functionality in Next.js seems to be malfunctioning

I am facing an issue with redirecting the user after submitting a form. I have a button that triggers a post request to my API route, which then inserts a row in the database. The goal is to redirect the user to / once everything is done. However, the retu ...

Is it possible to pass a random variable into an included template in Jade?

In my jade template called 'main page', I have a reusable template named 'product template'. The 'product template' is designed to display dynamic data and needs to be flexible enough to be used in multiple pages without being ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Prevent the countdown timer from resetting every time I refresh the page

Whenever I refresh my page, the timer starts over. I want it to pick up from where it left off until it reaches 0. This is my JavaScript code for handling the timer: var target_date = new Date().getTime() + (1000*3600*48); // set the countdown date var ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

Utilizing onMouseEnter and onMouseLeave events in React using hooks

My goal is to create a drop-down menu with a delay, allowing users to hover over the child list items before they disappear. However, I seem to have made an error somewhere but can't pinpoint it. It's likely just a simple mistake that my eyes are ...

Create a CSV file through an MVC Web API HttpResponse and retrieve it using AngularJS for downloading

I am attempting to create a CSV file from my web API and retrieve that file using angularjs. Below is an example of my API controller: [HttpPost] public HttpResponseMessage GenerateCSV(FieldParameters fieldParams) { var output = new byte[ ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...