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

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

When running `npm install`, it attempts to install version 1.20.0 of grpc even though version 1.24.2 is specified in

After running npm install on my React-Native project, an error occurred stating that it was attempting to install gRPC version 1.20.0, but my package.json and package-lock.json specified gRPC version 1.24.1. I attempted to fix the issue by adjusting the v ...

Tips for extracting particular information from a website and displaying it within my application

While I have searched for a solution to my problem, I couldn't find an answer that fits my specific needs. I am attempting to extract specific information (highlighted in red) from this website: . I understand that JSON parsing can retrieve this data, ...

What is the best way to retrieve a particular div element from a webpage?

I'm having trouble retrieving a specific div element (specifically with the attribute id="vung_doc") from a website. Instead of getting just that element, I seem to be getting almost every element on the page. Any ideas on what could be causing this i ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Invoking a function to display text when a selection is changed

I am trying to implement a jQuery function that displays a dropdown list with the options "One" and "Two": <select name="filter" data-userid="3" onchange="getPoints(this.value)"> <option value="one">One</option> <option value= ...

What is the best way to transform this unfamiliar CSS element into JavaScript code?

I'm facing an issue where I want to animate a CSS image based on time constraints, but since it's in CSS, I'm unable to achieve the desired effect. The animation in question is not the sun itself, but rather a yellowish half-circle animation ...

Utilize MySQL to populate highcharts with data

Learning the ropes of web programming, I have a personal project to monitor expenses. Simply put, my database stores data on total expenditures for this month and last month. I am able to display it manually (via echo), but I'm struggling to pass the ...

Changing from Basic to JavaScript?

Good evening, I am looking to convert this example code from Basic to JavaScript. Since JavaScript does not support the "Go To" command, I would appreciate it if you could help me with the translation. Thank you in advance. 10 x = 1666.66 20 y = 1.007897 ...

Adjusting the height of a card in Reactstrap

I am currently exploring Reactstrap and aiming to ensure a specific Card adjusts according to the size of the window by setting its aspect ratio using percentages rather than pixels. Interestingly, while adjusting the width works as desired, I'm faci ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

Can you provide tips on leveraging CSS as a prop for a Vuetify v-tab component?

Currently, I am in the process of updating my website to simplify color palette swapping. We are still experimenting with different colors that work well together. Our stack includes Vue and Vuetify, with SCSS generating our primary CSS file. Most of our c ...

Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request... Let's take a look at my HTML file named add-user.html: <script ...

minimize the size of the indigenous foundation input field

Currently incorporating this code snippet into my application: <Item fixedLabel> <Input style={{ width: 0.5 }}/> </Item> The fixedLabel element is extending the entire width of the screen. I have attempted adju ...

Modify picture properties when listbox is altered using jQuery

I need to set up a unique album gallery display where different folders are selected based on the item chosen in a selectbox. Below is the HTML code: <select name="album" id="album" onChange="changeimage();"> <option value="0" selected disab ...

Exploring the dynamic data loading feature in Vue 3 by fetching data from the server and displaying it using a v-for

I am encountering an issue where I want to display data dynamically from a database using a v-for loop. However, when I attempt to push new data into the array, they show correctly in a console.log() but do not reflect any changes in the template. I have ...

Utilizing AJAX in Tables: Implementing an Onclick Function in a Button within a Table to Access JSON Data

I am trying to trigger a function by clicking on a button and passing the position's ID as a parameter, but I am facing some difficulties in understanding how to achieve this with the given syntax. Can anyone guide me through this process? functi ...

VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form: pubs/UpdateProfile.vue <template> <confirm title="Edit Pub" ok="Save pub" :show="show" v-on:save="sa ...

What is the best way to augment an AJAX array response with additional data?

I'm working on an AJAX request and I need to add additional properties to the response I receive. Can anyone offer some guidance? Here is the AJAX request code I'm using: var form_data = {}; $.ajax({ type: "GET", url: "../../../sample_ ...