Discovering the proper way to choose the HTML ID associated with a Django variable in JavaScript

I am working with an ID in HTML that is assigned to a Django variable containing ads ID. I need to add this ads ID to a favorite list using local storage (cookies). The challenge I'm facing is that the ID is inside a loop and each ad has a different ID. How can I select the specific ID when the user clicks on the corresponding icon?

Below is a snippet of my code:

{% for item in result %}
    <span id="favouriteBtn" style="color:#ccc" title="add this post to favorite list"> &#9734; </span>
{% endfor %}

The ID format should be as follows:

id={{item.id}}

Here is part of the JavaScript function:

$('#favouriteBtn').click(function(){
currentAddFav();

I aim to set the ID as :

id={{item.id}}

and then be able to identify the specific ID clicked by the user. How can I achieve this?

The currentAddFav function looks like this:

function currentAddFav(){
if(localStorage.getItem('favourites')){//If there are favourites
    var storage = JSON.parse(localStorage['favourites']);
    if (storage.indexOf('data-item-id') == -1) { 
      // # not found
      storage.push('data-item-id');
      localStorage.setItem('favourites', JSON.stringify(storage));
    } else {
      // # found
      console.log('item already in favorites')
    }

}           
else
{//No favourites in local storage, so add new
    var favArray= [];
    favArray.push('data-item-id');
    localStorage.setItem("favourites", JSON.stringify(favArray));
    console.log('New favorites list');
}

}

Answer №1

If you want to customize your span by adding a 'data-item-id' attribute with the same value as your item's id, you can make the following adjustments:

{% for element in data %}
    <span id="favoriteButton" onclick="addToFavorites({{ element.id }})" style="color:#ccc" title="add this item to favorites list"> &#9734; </span>
{% endfor %}

The function "addToFavorites" will take care of the remaining steps, such as storing the selection in a cookie or similar process.

Example structure of the "addToFavorites" function:

function addToFavorites(item_id){
    if (localStorage.getItem('favorites')) { // Check if there are already saved favorites
        var storage = JSON.parse(localStorage['favorites']);
        if (storage.indexOf(item_id) == -1) { 
          // Item not found in favorites
          storage.push(item_id);
          localStorage.setItem('favorites', JSON.stringify(storage));
        } else {
          // Item is already in favorites
          console.log('item is already favorited')
        }

    } else { // No existing favorites, create new entry
        var favItems = [];
        favItems.push(item_id);
        localStorage.setItem("favorites", JSON.stringify(favItems));
        console.log('New favorites collection created');
    }
}

Answer №2

To achieve this, you can follow these steps:

{% for element in data %}
    <span id="{{ element.id }}" style="color:#999" title="click to add to favorites">&#9734;</span>
    <script type="text/javascript">
        var selected_id = "{{ element.id }}";
    </script>
{% endfor %}

Once the page is fully loaded, you can implement a click event on the selected_id

$('#' + selected_id).click(function () {
        addToFavorites();
});

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

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

Attempting to upload an item using ThreeJs

Can someone assist me with loading an object file from my local browser in Threejs ( Rev 71)? I keep encountering an error that says loadModel.html:1 Uncaught SyntaxError: Unexpected token #. Even after trying to load the object file using chrome --allow- ...

Hover without proper anchoring / move to section on click without anchor tag

I need assistance with a jump tab feature I am implementing on my portfolio website. I have encountered a couple of issues that I could use some help with. https://i.sstatic.net/8hwgL.png <ul class="section"> <li><span>home& ...

Determine the exact location of where the mouse was clicked within the

I've been attempting to determine the position of a click when a user clicks anywhere on the window. I came across this code in various tutorials, but unfortunately, it doesn't seem to be functioning as expected. (function( $ ) { $( document ...

How to change the video source on Internet Explorer

When setting the source of a <video> tag with JavaScript: $("#video-player").attr("src", '/DownloadCenter/GetFile?path=' + file.Path); Initially setting the source is not an issue, but using the same snippet multiple times results in the ...

Retrieve information from a local API using Next.js

While working with Next.js api today, I encountered an issue. I needed to fetch data from my internal API in getStaticProps. However, the documentation advises against fetching local API directly in getStaticProps and instead suggests importing the functio ...

Troubleshooting issue with Django development server causing HTML5 video element to become non-seekable

My Django app is currently serving a webpage with an HTML5 video element, but I've encountered a strange issue. The video.seekable property is returning a timeRanges object with a length=0, when it should actually be length=1. Unfortunately, this mea ...

Traversing a JavaScript object's array using AngularJS

As someone who is brand new to coding, I am embarking on the journey of building a basic website using AngularJS. However, I've hit a roadblock when it comes to looping through an object array in a controller and displaying each item in a directive te ...

The LatinSquare.js script has exceeded the maximum call stack size limit

In my current project, I am utilizing the latin-square library for node.js within a loop to search for a specific pattern. However, I encountered an error after running the script for 2 minutes: RangeError: Maximum call stack size exceeded var latin ...

Ways to display the number of files that have been chosen

I have included the code below in my project, and I am looking to customize the default style of the file selection button. However, after selecting files, the total count of files is not displayed. Is there a way to show the total count of selected files ...

Tips for preventing the repetition of values when dynamically adding multiple values to a text box using JavaScript

I am working on a function that adds multiple unique values to a hidden field. It is currently functioning correctly, but I want to ensure that the values added to the hidden field are unique and not duplicated if entered more than once. The select box wh ...

Relocating the output of JavaScript to a different location

I'm currently facing an issue with transferring my JavaScript output (start) from the black box to the grey box. I am unsure about what needs to be included in the functions (moveRight and moveLeft) for the transition to occur smoothly. Even after re ...

The Next.js 404 error page seems to be malfunctioning. Any ideas on what might be causing this issue?

Whenever I attempt to access a non-existent route, the home page loads without changing the URL. My expectation was to see a 404 error page. To handle this issue, I created a custom error page called pages/_error.js import Page404 from './404'; ...

NodeJS Post Request Issue: Parsing Numbers in URL Parameters Resulting in NaN

I'm fairly new to working with NodeJS. Currently, I am facing an issue where all the integers in the parameters are being passed as NaN when making a POST request. In the snippet below, you can observe that the parameters have actual numbers assigned ...

Is there a way to determine which option is currently highlighted in Internet Explorer before it is actually chosen?

Despite the fact that IE does not support mouse events on <option> elements, it does highlight the option under the mouse cursor when you open a dropdown list. Is there a way in JavaScript to capture this highlighted option as the user moves the mous ...

I am attempting to incorporate a new font into my react native application, however, I am encountering an error indicating that a JSX tag has not been properly closed, despite my best efforts to

Adding fonts to my app has hit a snag with this error message popping up SyntaxError: C:\Users\arich\Documents\efees\App.js: Adjacent JSX elements must be enclosed in a tag. Did you mean to use a JSX fragment <>...? (69:5) ...

Tips for importing a JSON file from your local directory in Vue.js

I've been attempting to load data from a local JSON file in Vue. My goal is to simply load the data from the file and assign it to a variable. I'm not sure if I'm on the right track or if I'm missing something essential in my approach. ...

Using Angular JS to filter ng-repeat with a combination of a field and a dropdown

There seems to be a lot of conflicting information online regarding this issue, but I am in search of a concise solution. My dataset consists of a list of countries around the world, including their name, ISO alpha code, region, and more. To display this ...

What causes the checkbox to automatically check the following checkbox after being checked?

I'm working on a small todo list application using Vue. The issue I'm facing is that when I check the first checkbox to mark a task as complete, the next task's checkbox gets automatically checked as well, but this does not happen with the l ...