Using jQuery to extract the value of an object from an <li> element and updating the class attribute of the <li> element

There is a div element:

<div id="ddDistr" class="searchBoxSortDistrict" tabindex="1">
  <ul id="ddd">
  </ul>
</div>

I have inserted HTML from json into it:

$("#ddd").html(" "), $.each(dis, function(
  index, value) {
    $("#ddd").append( "<li><a style=\"cursor: pointer;\">"
    + value.fieldName + "("
    + value.count + ")</a></li>");
   }
);

I am trying to change the class of onclick <li> to .active.

$('#ddDistr li > a').click(function() {
  console.log('dd');
  $(this).siblings('li').removeClass('active');
  $(this).addClass('active');
});

However, this code is not working. Can you help me identify the issue?

Furthermore, I want to retrieve value.fieldName from the active <li> element and send it via POST.

How can I achieve this? Any suggestions?

Answer №1

When using a click event for an anchor element, keep in mind that $(this).siblings('li') won't work as expected since `li` elements are not siblings of the anchor. Instead, you should use something like

$(this).closest('li').siblings('')
.

Update: To attach events to dynamically generated elements, you will also need to use event delegation.

To add a class to the parent `li` of a clicked anchor:

$('#ddDistr').on('click', 'li > a',function() {
    console.log('dd');
    $(this).closest('li').siblings().removeClass('active');
    $(this).closest('li').addClass('active');
});

To add a class to the clicked anchor tag:

$('#ddDistr').on('click', 'li > a',function() {
  console.log('dd');
  $(this).closest('li').siblings().find('a').removeClass('active');
  $(this).addClass('active');
});

Answer №2

ul is not a relative of span, it's actually its child.

This fact becomes evident when you observe ul > span.

To resolve this issue, simply update your code to utilize child():

$(this).child().toggleClass('highlighted');

You can also attach the click function directly to the specific ul element.

Furthermore, per the advice of user1234, learn more about utilizing .on() and event delegation. If you define the click function before creating your HTML elements, it may fail as the function will only be applied to pre-existing content. This emphasizes the importance of delegating events to a pre-existing container for effective functionality.

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

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

Having trouble rendering an HTML webpage using Flask's RESTful API? Your webpage might be displaying improperly

Trying to display an HTML page on local host using a restful flask API. The content of the HTML page appears as a string with "" instead of rendering the actual page. class data(Resource): def get(self): #return "Welcome!" return rende ...

Ways to center-align this menu (Spanish language)

I am working on optimizing the alignment of the menu on my website: My goal is to center the menu, as the English version looks good. #site-navigation { width: 980px; margin: 0 auto; text-align: left; } After analyzing the code, we have iden ...

Getting the AJAX response back to the main page

I'm currently working on a user registration form within a jQuery modal dialog. Once the form is filled out and submitted, the data is successfully sent to a MySQL database using jQuery/Ajax. However, my challenge lies in displaying the updated data ...

Creating a Pop-Up on Website Load with HTML, CSS, and Jquery

<script> // utilizing only jquery $(document).ready(function(){ $('#overlay-back').fadeIn(500,function(){ $('#popup').show(); }); $(".close-image").on('click', function() { $('#po ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

Steps for modifying the CSS class of an <a> tag with Jquery/Javascript

I am attempting to dynamically change the class of a tab on the dashboard based on the selected page. In the dashboard, there are 3 tabs: <div> <ul class="menu"> <li class="MenuDashboard"><a href="#" >Dashboard</a&g ...

Creating Bubble Charts using npm highcharts with error code #17

I am attempting to create a bubble chart using Highcharts with the npm version, but I keep encountering error #17. I have tried importing highcharts-more without success... Here are my imports: import $ from "jquery"; import _ from "underscore"; import L ...

Converting rotation into a directional vector

I have a Three.js object and I am able to read its rotation. However, I am looking for a way to extract a vec3 that indicates the direction in which the object is currently rotated. Can someone provide guidance on how to achieve this? ...

Why does my jQuery code target all the text values?

Looking to grab a specific table cell number and multiply it by an input value on focusout, but having trouble with the selector grabbing all cells with "front" in the name. Check out the code below: jquery $(document).ready(function(){ $(".percent") ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Changing the container's height in an HTML document

enter image description hereim struggling to change the height of the white dash container, and I can't quite figure out how to do it. Here is the code, any help would be appreciated: analytics.html : {% extends 'frontend/base.html' %} {% l ...

Unable to use saved images with jQuery Slider

I'm currently facing an issue with adding a jQuery slider to my website. It seems that the slider is not displaying images that are saved on my computer, only images from external websites. Below is the code snippet where I have included an image fil ...

Conflict between jQuery and dynamically changing page content

I've come across multiple discussions on SO regarding similar topics, but I haven't been able to successfully troubleshoot my code to achieve the desired functionality. I'm currently working on an application that involves dynamically chang ...

Unable to establish connection between Router.post and AJAX

I am currently in the process of developing an application to convert temperatures. I have implemented a POST call in my temp.js class, which should trigger my ajax.js class to handle the data and perform calculations needed to generate the desired output. ...

Disable location prompt feature when using AngularJS with Maps API

For my web application, I developed a feature that includes a map with custom markers using Angular loops: <map data-ng-model="mymap" zoom="4" center="[38.50, -95.00]" style="heigth:375px"> <div ng-repeat="item in list"> <marker pos ...

Detecting the clicked link within a React component

My NavBar features a Logo that includes a Link to the Home page "/". The application kicks off from the main page and as per user selections, the UI will adapt accordingly. To offer users a chance to reset everything if they are currently on the Home compo ...

Enhance jQuery with additional features using Bootstrap

My website utilizes Bootstrap 4, which comes with the slim version of jQuery that does not include effects. I attempted to add the normal version of jQuery alongside the slim version in order to access the effects, but it was unsuccessful. I even tried r ...

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...