Adding Fruits Exercise

Hey all, I’ve created a Frankenstein and need some help with dissection.

In my button click function to add the input I’m getting a reprint of the entire array each time and I can’t seem to think of a way instead to just add the new fruit to the list without printing the entire list again and again.

        <h1>My favorite fruits</h1>

        <input class="fruitInput" type="text" placeholder="add fruit">
        <button>Add</button>

        <ol class="fruitList">
        </ol>

        <script>

            let fruits = ["Pear","Mandarin","Banana","Pineapple"];
            
            let list = $(".fruitList");

            $("button").click(() => {
                    let x = $(".fruitInput").val();
                    fruits.push(x);
                    $.each(fruits, (index, value) => {
                    $("<li/>").text(value).appendTo(list);
                });

                });

        </script>
1 Like

Greetings @chommp,

I see in your code that you’re missing a simple line of instruction.
For every click, you need to make sure the list is cleared first then add the new list.
You could do this –

let fruits = ["Pear","Mandarin","Banana","Pineapple"];
           
           let list = $(".fruitList");

           $("button").click(() => {
                   let x = $(".fruitInput").val();
                   fruits.push(x);
                   $(".fruitList").html(""); // added this
                   $.each(fruits, (index, value) => {
                   $("<li/>").text(value).appendTo(list);
               });

               });

If you don’t want to loop through the list, again and again, you could loop the first time and add all the initial fruits. Then you could add new fruits one by one without looping. This is a more efficient way of adding items to a list. The implementation would be as follows –

 let fruits = ["Pear", "Mandarin", "Banana", "Pineapple"];

        let list = $(".fruitList");
        $.each(fruits, (index, value) => {
            $("<li/>").text(value).appendTo(list);
        });
        $("button").click(() => {
            let x = $(".fruitInput").val();
            fruits.push(x);
            $('.fruitList').append('<li>' + x + '</li>');
        });

Hope this clears your confusion.

Happy Learning! :slight_smile:

2 Likes

Thank you! This helps a lot. Really appreciate the feedback and refraction!

1 Like