Is there a way to assign a sessionStorage key by clicking on certain elements in HTML?

I have encountered an issue while attempting to set a value in the sessionStorage. The problem lies in storing the sessionStorage "key" differently based on the item clicked. For instance, if I click on the first view chat, I should store a key of "1", and for the second view chat, a key of "2". These keys are derived directly from the ajax call below. Each HTML element is duplicated based on the number of entries received from the AJAX "GET" method call. Therefore, each box below has a unique sessionStorage "key" that needs to be set when clicking on the respective box's "view chat".

https://i.sstatic.net/2ogkP.png HTML File


<!-- Main content -->
<section class="content">

    <!-- Default box -->
    <div class="card card-solid">
      <div class="card-body pb-0">
        <div id="chatItemBox" class="row d-flex align-items-stretch">
          <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch chatItemBox">
            <div class="card bg-light">
              <div id="chatItemBoxUsername" class="card-header text-muted border-bottom-0">
                Digital Strategist
              </div>
              <div class="card-body pt-0">
                <div class="row">
                  <div class="col-7">
                    <h2 class="lead"><b id="chatItemBoxName">Nicole Pearson</b></h2>

                    <strong><i class="fas fa-envelope mr-1"></i> Email</strong>

                    <p id="chatItemBoxEmail" class="text-muted">HI
                    </p>

                    <hr>

                    <strong><i class="fas fa-phone mr-1"></i> Contact</strong>

                    <p id="chatItemBoxContact" class="text-muted">HI
                    </p>

                    <hr>

                  </div>
                  <div class="col-5 text-center">
                    <img src="../../dist/img/user1-128x128.jpg" alt="" class="img-circle img-fluid">
                  </div>
                </div>
              </div>
              <div class="card-footer">
                <div class="text-right">
                  <a href="view-chat.html" class="btn btn-sm bg-teal" onclick="sessionStorage.setItem('chatId', chatId)">
                    <i class="fas fa-comments"></i> View Chat
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /.card-body -->
      <div class="card-footer">
        <nav aria-label="Contacts Page Navigation">
          <ul class="pagination justify-content-center m-0">
            <li class="page-item active"><a class="page-link" href="#">1</a></li>
            <li class="page-item"><a class="page-link" href="#">2</a></li>
            <li class="page-item"><a class="page-link" href="#">3</a></li>
            <li class="page-item"><a class="page-link" href="#">4</a></li>
            <li class="page-item"><a class="page-link" href="#">5</a></li>
            <li class="page-item"><a class="page-link" href="#">6</a></li>
            <li class="page-item"><a class="page-link" href="#">7</a></li>
            <li class="page-item"><a class="page-link" href="#">8</a></li>
          </ul>
        </nav>
      </div>
      <!-- /.card-footer -->
    </div>
    <!-- /.card -->

  </section>
  <!-- /.content -->

Script


    $.ajax({
        url: 'http://localhost:8080/Retail-war/webresources/chat/retrieveChatsForUserForMerchant/' + uId,
        type: 'GET',
        dataType: 'json',
        // Fetch the stored token from localStorage and set in the header
        headers: { "Authorization": 'Bearer ' + sessionStorage.getItem('accessToken') },

        success: function (data) {
            // Get all chatItemBox by class
            var chatItemBox = document.getElementsByClassName('chatItemBox');

            console.log(chatItemBox)

            // Get the last one
            var lastChatItemBox = chatItemBox[chatItemBox.length - 1];

            count = 0

            $.each(data, function (key, entry) {
                var chatItemBoxUsername = document.getElementById('chatItemBoxUsername').innerHTML = entry.createdBy.username
                var chatItemBoxName = document.getElementById('chatItemBoxName').innerHTML = entry.createdBy.name
                var chatItemBoxEmail = document.getElementById('chatItemBoxEmail').innerHTML = entry.createdBy.email
                var chatItemBoxContact = document.getElementById('chatItemBoxContact').innerHTML = entry.createdBy.contactNumber

                // Clone it
                var newChatItemBox = lastChatItemBox.cloneNode(true);
                newChatItemBox.className = 'col-12 col-sm-6 col-md-4 d-flex align-items-stretch chatItemBox' + count;

                count = count + 1

                console.log(newChatItemBox);

                document.getElementById('chatItemBox').appendChild(newChatItemBox)
                console.log(entry)
            })
            $('.chatItemBox').attr('id',  'toHide')
            $('#toHide').remove();
            console.log(data)
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });  

Answer №1

In essence, the first parameter serves as the key while the second parameter represents the value for sessionStorage.setItem.

Apply the following code for the 1st chat window:

onclick="sessionStorage.setItem('1', chatId)"

Utilize this code for the 2nd chat window:

onclick="sessionStorage.setItem('1', chatId)"

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

Using node.js for synchronous callbacks in node.js programming

I am new to node.js, and from what I've gathered, each callback creates a new event that can be executed in parallel. For instance, consider the following code with a callback: function testFunction(var1){ s3.head(var1, function(data, err){ ...

What is the most effective way to navigate to a different webpage?

I'm facing a challenge with redirecting to another page after inserting data. I've tried various methods, but nothing seems to work. Can anyone guide me on how to achieve this successfully? let express = require("express"); let app = ex ...

Managing multiple route redirections in express.js

Recently, I started working on an express app and it's my first time using this framework. I have multiple routes that I want to redirect to one specific route without duplicating code like this: var router = require("express").Router(); router.all( ...

Stylish CSS selector

Is there a way to target CSS path based on the style of an element? For instance, if I have two ul elements on a page - one with a style of list-style-type: lower-alpha;: <ul start="1" style="list-style-type: lower-alpha;"> and the other ul without ...

Troubleshooting techniques for resolving CSS issues with the video.js package in ReactJS

When using video.js in react to build a video player, I encountered an issue with the npm package not providing its inbuilt CSS. How can I add the inbuilt CSS of video.js? Instead of the control bar, I am getting something different than what is shown in t ...

Refreshing on current page with PHP [unveiling a new world of content]

My application consists of 4 pages that utilize PHP sessions. On page 1, users input their username and password, on page 2 they provide additional information, page 3 displays results and requests more details, and finally page 4 is the success page. Upon ...

What is causing the issue with my navbar 'bars' not showing up properly on mobile devices?

My navbar is not displaying the ul bars when I click on the button to open them in mobile view. Here's what currently happens: https://i.sstatic.net/fFIzM.png What I actually want it to look like is this: https://i.sstatic.net/a8fSK.jpg However, w ...

Guide to implementing Ajax with the CodeIgniter label functionality

My CodeIgniter website features two labels with radio buttons. https://i.stack.imgur.com/0heIo.jpg Upon loading the page, all course names are displayed. I would like to implement a feature where clicking the button will only show relevant course names. ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

Guide to making the top margin of Chinese characters consistent on all web browsers

Currently, I am working on a website that features flashcards for Chinese character learning. The issue I am facing is that Internet Explorer displays fonts slightly higher on the line compared to other browsers I have tested. Although this may seem insign ...

Problem with Submitting Form using Search Bar

I've tried everything, but I can't seem to get this search form to submit. <div id="search_bar_container" style="z-index:99999"> <div class="container"> <form action="tour-list-search-results.php" method="post" name="searc ...

Troubleshooting issues with Three.js and .obj file shadows

I've been diving into learning Thee.js, and while it's fairly straightforward, I've hit a roadblock with getting shadows to work. Despite setting castShadows, recieveShadows, and shadowMapEnabled to true in the appropriate places, shadows ar ...

Can you explain the distinction between these two Redux reducer scenarios?

While looking at someone else's code for a reducer, I noticed this snippet: export default function reducer(state, action) { switch(action.type) { case 'ADD_TODO': Object.assign({}, state, { ...

What is the best way to pass an object into a method within a select element using Vue

Kindly review the following code snippet. <tr> <td>Select Timeslot</td> <td colspan="2"> <select class="form-control" v-on:change="onTimeSlotClick"> <option v-for="slot of slots"> <l ...

Centering Slides Vertically in Slick Carousel with Bootstrap 4 Beta

I have spent approximately 2 hours searching and attempting over 15 solutions, but none of them have been successful. The issue involves a slick-slider structured as follows: <section id="testimonial-section" class="pt-4 pb-0 px-4 bg-dark text-white"&g ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...

d3js graphics, Opt for utilizing json strings over json file

My first experience with d3js was while utilizing the Line Chart Sample provided by this link. Despite successfully loading the data as seen in Firebug, the chart itself failed to display the data. I am unable to identify the issue and would greatly apprec ...

What's preventing me from accessing .NET Web Service methods using AJAX and jQuery Mobile?

Why can't I access the web service's 'hello world' method despite trying numerous approaches? I'm unable to determine the cause of the issue. Here is the structure I have: WebService : [WebService(Namespace = "http://tempuri. ...

What is the best way to ensure a button's size remains constant even when new text is inserted?

https://i.sstatic.net/K4QDt.png I created these buttons for a tic-tac-toe game as a way to improve my React skills. I'm aiming to have all the boxes form a perfect square shape. However, the box size changes when text is added. While I'm workin ...