Iterating through div elements with JQuery to construct a multiline string utilizing the information stored in a data attribute

Two questions are on my mind:

1.) Looking at my code, I have several divs with onclick events linked to the "callout panel notes" div. When this div is clicked, it accesses the data-category attribute using $(this).parent().parent().siblings().first().data("category"); although it works, it appears messy. I attempted to use parents().last().data(...) but that did not work. Any suggestions on a more efficient way to achieve this would be greatly appreciated.

2.) My second question pertains to selecting content within specific categories. After clicking on some divs, they get assigned a "selected" class. Later on, I need to fetch the selected content and send it through ajax for processing. Since there are multiple categories, I only want to loop through those belonging to data-category="a". Can anyone provide guidance on looping through data-category="a" divs with the .selected class and building a multi-line string with their respective data-response-text values?

Here is the HTML structure:

<div class="row responses panel">
    <div class="small-12 column" data-category="a">
        <h3>Responses</h3>
    </div>

    <div class="small-12 column">
        <div class="callout panel notes" data-response-text="Info 1">
        Info 1
        </div>
    </div>

    <div class="small-12 column">
        <div class="callout panel notes selected" data-response-text="Info 2">
        Info 2
        </div>
    </div>

    <div class="small-12 column">
        <div class="callout panel notes selected" data-response-text="Info 3">
        Info 3
        </div>
    </div>

    <div class="small-12 column">
        <div class="callout panel notes selected" data-response-text="Info 4">
        <div class="remove-response"></div>
        Info 4
        </div>
    </div>

    <div class="small-12 column">
        <div class="add-new-box">
            <div class="add-new">
            Add Response
            </div>
            <div class="add-new-text">
                <input class="text-response" type="text" placeholder="Response">
            </div>
        </div>
    </div>

</div>


<div><span class="button">Submit</span></div>

Answer ā„–1

To start off, you have the option to use the following code snippet:

$(this).closest('.row.responses').children(':first').data('category');

If .row or .responses are unique identifiers for elements at that level, go ahead and utilize them individually.

Moving on to the second part, assuming that "content to be associated with the data-category a" refers to elements within .row.responses where the first element has data-category="a", you can execute the following code:

var str = "";
var sls = $('[data-category="a"]').parent().find('.selected');
sls.each(function() {
    str += $(this).data('response-text') + "\n";
});

Answer ā„–2

How to approach the first question:

$(this).find('[data-category]').data();

Create a function that can retrieve the necessary data from each panel's .selected class.

function extractData(panel) {
    var $selected = $(panel).find('.selected');
    var extractedData = [];
    for (var i = 0; i < $selected.length; i++) {
        extractedData.push($selected.eq(i).data().responseText);
    }
    return extractedData;
}

var requiredData = extractData($('the-panel-in-question'));

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

Possible alignment problem when converting Angular ng-repeat to PDF or printer using CSS

While working on generating tickets for printing using AngularJS, I noticed that there is an offset of approximately 5 pixels between the first and last ticket out of the 1000 tickets I tried to create. As I was tinkering with my code, the output appeared ...

What could be causing API requests to be directed to the incorrect URL in Vue.js 2?

I've been experimenting with learning Vue.js 2 and routing, and I'm puzzled by a specific issue. Whenever I navigate to routes other than the home ('/') route, the localhost URL is somehow added to the API calls. Here's an example ...

What is the best way to position two divs side by side at the bottom of the

When trying to align my second div with the first one, I face an issue. If the text above the first blue box is longer, the second div appears to be outside the line of the box. Changing the relative position doesn't solve this problem either. When th ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

My browser is being overwhelmed by jQuery's each() function while trying to manipulate a large set of elements. How can I optimize my code to reduce the strain on my browser

Currently, I am utilizing two custom plugins to identify and style all the radio/checkbox inputs and select boxes within a form. The issue arises when dealing with a large form that contains numerous checkboxes, causing Firefox to stall as the plugin atte ...

The eclipse android emulator does not support JavaScript and JQuery

<html> <head><title>XYZ</title> <!--<script src="jquery.gamequery-0.7.0.js"></script>--> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script ...

Problems with Emulating Chrome | Using Media Queries

Currently, I am in the midst of testing my responsive website and I have encountered an issue with the Chrome emulator. When I select a specific device like "iPhone 6", the responsive views are not displaying correctly. Instead, unsightly scroll bars appea ...

Charts.js fails to refresh data following an AJAX call

Having recently delved into the world of js and jquery, I managed to successfully display a chart using Flask and an Ajax request. However, I've hit a roadblock when it comes to refreshing the charts data. If I create a new chart each time as demonstr ...

Alphabetic divider for organizing lists in Ionic

I am currently working with a list in ionic that is fetched from a controller and stored in localStorage. My goal is to add alphabetic dividers to the list, but I am facing some confusion on how to achieve this. Here is a snippet of the code: app.js $ion ...

Verify if the username is in use using an ajax request

Currently, I am in the process of verifying the existence of a username in the database while filling out a registration form using Ajax. This is the script I am using: $(document).ready(function() { //minimum characters required for username ...

Guide to ensuring only one Accordion opens at a time in Elementor

I created a custom accordion in elementor with CSS and JavaScript, but I'm facing an issue where the tabs stay open when others are opened. How can I modify the code to make sure only one tab is open at a time? Below is the CSS code snippet: body ...

Ways to invoke a function simultaneously with the calling function in the React Context API

I need to implement a function update() within the context of WebContextProvider. This function will in turn call another function updateAgain() also located within WebContextProvider. Here is the code snippet for reference. import React, { createContex ...

The updated syntax for the Dojo XHR request is failing to retrieve the data as intended

As the title suggests, I am currently implementing the new syntax for dojo/request/xhr. However, I have encountered an issue where the data does not load properly and throws an error. Surprisingly, using the old syntax with the same URL yields the desired ...

Embed the YouTube video using the URL in the video tag

I tried using the <video> tag, but I'm having trouble getting it to play videos from YouTube. Even though I found this http://jsfiddle.net/wCrNw/, it doesn't seem to work as expected. I also consulted Show Youtube video source into HTML5 ...

Securely Passing API Tokens in JavaScript: Best Practices

This script fetches data from an API and displays it on the HTML page using AJAX and Javascript. The TOKEN used for the API is visible in the Javascript code. I believe this approach is not secure as anyone with access to the page can view the token. Are ...

Moving a Ball Back and Forth Using Three.js

Iā€™m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence. var geometry = new THREE.SphereGeometry( 5, 32, 32); var material = new THREE.MeshPhongMateri ...

There seems to be a missing row in the PHP looped output of the mySQL table

I am facing an issue with a MySQL table that contains data. I am using PHP code to display this data on an HTML page and set up JavaScript variables before the page loads. However, there seems to be a problem with the loop as it is dropping or not showing ...

Electron generates a unique landing page for your first launch

Can you help me create a feature on a webpage that only appears once and then never shows again? Similar to the "Never show me again" checkbox in Visual Studio Code upon first launch. ...

Building a blank page with a successful AJAX loading prototype

I'm currently working on a Magento project and encountering an issue while attempting to load more products with the click of a button. Although I can see the products loading, it ultimately leads to a blank page afterwards. I am unsure of what coul ...

Create a form with a mailto link that includes a subject line containing "XXXX" followed by user input

Need help with customizing the email subject along with the user's name from a form input <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8f939199939299bc8593898e8f958899d29f9391">[email protec ...