Preventing Repetition in an HTML List using JavaScript

My HTML list is populated with values from JSON, and I have a button on the page.

<button onclick="printJsonList()">CLICK</button>

This button triggers the following JavaScript function:

function printJsonList(){
    console.log(ctNameKeep);
            var ctList = []; var ctRight = [];
            var ctNameKeep = [];
            var $tBody = $("#La");
            var $rbody = $("#accordian");

            $.getJSON('https://api.myjson.com/bins/n0u2o' , function (data) {
                    data.forEach((CTLIST) => {
                        if(ctNameKeep.includes(CTLIST.ct)){
                            return ;
                        }
                        else {
                   ctNameKeep.push(CTLIST.ct);
                        $tBody.append(`<li class="list-group-item" id="rl">
                        <span id="nameOfCt">${CTLIST.ct}</span>
                                <a href="#${CTLIST.ct}" class="btn btn-danger show" data-toggle="collapse">View More</a>

                         <div id="${CTLIST.ct}" class="collapse valueDiv">
                              <label>TTS</label> <input id="tts" type="text" value="${CTLIST.tts}"><br>
                              <label>Topic Level</label> <input id="topic_level" type="text" value="${CTLIST.topic_level}"><br> 
                              <label>TimeOut</label> <input id="timeout" type="text" value="${CTLIST.timeout}"><br>
                                <label>To be shown individually</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
                              <label>check for geometry</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
                              <label>check_for_image_labelling</label> <input id="check_for_image_labelling" type="checkbox" ${(CTLIST.check_for_image_labelling && 'checked')}> <br>         
                     </div>        

                        </li>`);
                    } //else 
                    });
            })
            console.log(ctNameKeep)
    }

I store the names of the items in an array and avoid printing duplicates. It works well on the first click, but when clicked again, it repeats the list creation. I want to prevent duplicate entries even after multiple clicks without using global variables. Any possible solutions or replacements?

https://i.sstatic.net/l72kT.png

https://i.sstatic.net/yNt9O.png

Answer №1

How to Bind a Function with Parameters

Imagine a scenario in which you have:

function printJsonList(ctNameKeep){
  someajaxcall(function(something){
    ctNameKeep.push(something)
  })
}

In this case, you can do the following:

const printJsonList2 = printJsonList.bind(null, [])

Now, whenever printJsonList2 is called, it will essentially call printJsonList([]).

You can customize the array being referenced according to your requirements.

So,

<button onclick="printJsonList2()"></button>

Implementing Components

The current trend involves creating components for different functionalities.

For instance, you could create a component specifically for handling a button click event.

const myBtn = ((btn => {
  let ctNameKeep = [] // Keeping ctNameKeep local
  function printJsonList(){ctNameKeep.push('..')}
  btn.addEventListener('click', printJsonList)
  return {someMethodsForYourComponent} // This may not be necessary
})(document.querySelector('button'))


const printJsonList = (function (ctNameKeep) {
  ctNameKeep.push(String.fromCharCode(65+Math.floor(Math.random()*26)))
  console.log('ctNameKeep', ctNameKeep)
}).bind(null, [])

;(btn => {
  let ctNameKeep = []
  function printJsonList () {
    ctNameKeep.push(String.fromCharCode(65+Math.floor(Math.random()*26)))
    console.log('anotherone', ctNameKeep)
  }

  btn.addEventListener('click', printJsonList)
})(document.getElementsByTagName('button')[1])
<div>
<button onclick="printJsonList()">clickbind</button>
<button>clickcomp</button>
</div>

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

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

After the decimal point, there are two digits

My input field is disabled, where the result should be displayed as a product of "Quantity" and "Price" columns ("Quantity" * "Price" = "Total"). However, I am facing an issue where the result often displays more than 2 digits (for example: 3 * 2.93), desp ...

Unable to select image inside linked container

I'm attempting to display a dropdown menu when the user clicks on the gear-img div using jQuery. However, because it's wrapped inside an a tag, clicking redirects me to a URL. I also want the entire div to be clickable. Any suggestions for a solu ...

The CSS property object-fit: cover is unable to properly display JPEG images with EXIF orientation greater than 1

I'm having trouble with my Angular app and creating a gallery of photos from my Samsung Galaxy. I am using the "object-fit: cover" css attribute for a nice design, but it only seems to work correctly when the image has an EXIF "orientation" property e ...

Search functionality in Laravel using Select2

I am currently facing an issue with the select2 jQuery plugin. I am unable to search for specific data that I need to display. Specifically, I am trying to search for a book name in my database within the branch of the company where I am located. This invo ...

Using jQuery Mobile to dynamically load content into a specific div element

Jquery Mobile operates by seizing control of a page and fetching content to inject into it. However, this poses an issue when attempting to inject additional content into the page. In my setup, I have an index.html and a page2.html file. I am configuring ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Concluding the dialogue once the post request has been successfully processed

My tech stack includes React, Redux, NodeJS, and ExpressJS. For the front-end, I'm utilizing material-ui. Within my application, I have implemented a dialog that allows users to input information and sign up. Upon clicking submit, a POST request is in ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Tips for incorporating a set offset while utilizing the scrollTop() function

I have successfully implemented a code that sets a position:fixed to a div when it scrolls past the top of the screen. The code I used is as follows: var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.o ...

Is there a way to access the initial element of the array within this variable assignment?

When utilizing the element id 10_food_select: var id = $(sel).attr("id").split("_"); An array is generated as follows: ["10", "food", "select"] The desired outcome is to have id = 10 (or whichever value is in the first element). This can be achieved l ...

The disappearance of data stored in .data() in JQuery

I've encountered an issue with a function that creates an anchor, stores data, and appends it to a div element. var x = $("<a class='randomclass'></a>"); x.data('foo', 'bar'); console.log(x.data()); ... $("&l ...

What is the method to verify if a variable in ES6 is constant?

I'm seeking advice on how to accomplish a specific task. I attempted using the try-catch method, but encountered some limitations: "use strict"; const a = 20; var isConst = false; try { var temp = a; a = a+1; a = temp; } catch (e) { isConst = ...

Position the Close Button within the CSS Cookie Consent Popup in perfect alignment

Having trouble aligning the close X button in my cookie consent popup to the center? I added a margin-top to adjust it, but I'm looking for a better solution. <div class="alert cookiealert" > By using our website you agree to our C ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

`"Error in accessing array index" occurred while trying to retrieve array data for the dataTable jQuery plugin`

Incorporating an ajax json response that will populate the dataTable jquery plugin with data retrieved from a server. The unique identifier for the table is #dataTable. Below is the code snippet for initializing the dataTable plugin: $(document).ready(fu ...

Update to react version 18.2.0, router-dom v6, and mui 5 for improved performance

Struggling to convert the following file or code into React's latest version and react-router-dom v6. I attempted it myself but encountered errors related to createBrowserHistory that I couldn't comprehend. My routes are stored in a JSON file and ...

What is causing the failure of this Web2Py ajax call to retrieve the variable value?

Here is an excerpt from my Web2Py view code: {{for candidate in rows:}} <div class="well col-sm-12"> <button type="button" name="up_button" onclick="ajax('{{=URL('default', 'arrow_button_callback')}}', [& ...

Decomposing LocalStorage data in React using JavaScript

How can I retrieve this element from localStorage? Although I am able to console.log(product.priceHistory), how do I access its price element? useEffect(() => { let productFromLocalStorage = localStorage.getItem(id); setProduct(JSON.parse(pro ...