Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone.

Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there are no divs in the drop zone at page load, I am planning to collect the ids using a save button along with text box input and dropdown menu selection.

Here's the snippet of code that I've experimented with:

$(document).ready(function() {
    $("#dropzone div").click(function() {
        var index = $("#dropzone div").index(this);
        $("#dropzone_drag").html("Index " + drag + " was clicked");
    });
});

Additionally, I have integrated jQuery for the text box functionality, which is functioning smoothly:

$(document).ready(function() {
    $('#save').click(function() {
        alert($('#name').val());
    });
});

Could you please advise me on how to retrieve the ids of dragged divs once they have landed in the drop zone?

Answer №1

Experimenting with different ideas, I ended up with this solution:

var ids = {};
$("#dropzone>div").each(function(i){
    ids[i] = $(this).prop('id');
});

Currently, it displays as undefined, but I successfully linked it to the save button to prevent it from appearing when the page is opened.

Any recommendations or suggestions?

Answer №2

From my understanding, .index(this) gives you the position of the element in relation to the list "#dropzone div", which may not necessarily have the elements arranged in the order you desire. However, if all your elements share a common class like ".foo_bar", it might be simpler to determine the id based on the clicked element.

Alternatively, if you are using this within a function and it refers to one of your "drags", extracting the id from this could be easier than trying to calculate indexes.

You could attempt this approach and see if it yields better results.

ids = {};
$("#dropzone>div").each(function(){
    ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});

The use of .replace() in the code snippet indicates that we are removing characters (specifically anything that is not a number) from the string, thus obtaining the actual numeric value instead of its position in the DOM.

If I have misunderstood your issue, please clarify any misconceptions and I can revise the response accordingly. Additionally, an HTML representation of the zones would be helpful for further assistance ;)

Answer №3

After trying different approaches, I found a solution that worked for me:

  <script>
  var div = document.getElementById('dropzone')
  </script>

I also added the following code to a button:

alert( div.innerHTML )

This allowed me to extract specific information from the div's HTML content, which I then pushed to the database.

Thank you to everyone who provided input and advice.

- Matthew

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

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

Validation in PHP and Javascript is only partially effective

I encountered an issue with my form validation setup that utilizes JavaScript, Ajax, and PHP. While the errors are correctly displayed when the form is filled incorrectly, I am unable to submit the form even if there are no errors. Clicking the submit butt ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

I have noticed that the share buttons on Sharethis.com only show up after I resize the viewport

After integrating share buttons from Sharethis.com, I noticed that they do not appear when the page is refreshed. However, when I resize the viewport, they suddenly show up. <!DOCTYPE html> <html lang="en"> <head> <script t ...

Div's HTML Classes are not triggering the Click Event

I'm attempting to create a custom function that will display notifications in the top right corner of my website, similar to how OS X notifications appear. Instead of relying on an external library, I am using jQuery as a resource. To house my notifi ...

The HTTPOnly cookie is not accessible within the getServerSideProps function in Next.js

Why isn't the jid cookie available in getServerSideProps using Next JS? Here's the scenario: https://i.stack.imgur.com/FLRGk.png The jid cookie is generated by an Expressjs API at https://api-dev.example.com. I'm attempting to retrieve thi ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...

Having trouble updating attribute through ajax requests

How can I set attribute values using ajax-jquery? Here are some snippets of code: HTML_CODE ========================================================================== <div class="col"> <ul class="nav nav-pills justify-content-end& ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Guide on extracting JSON data from jQuery containing an array in C#

Looking for a way to extract array data from JSON in C#? Here is an example of the AJAX code: $.ajax({ type: "GET", url: "/Weather/GetWeather", data: { "a": ["1,","2&"], "b" : 4 }, success: onSc ...

Avoid displaying identical items when rendering a page from JSON data

I am using ajax and json to render a page. The structure of my json is as follows: {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]}. I want to load the data using ajax only once if 'points' have duplicates in any of the ...

Can you tell me the CSS equivalent of the SASS/SCSS expression "&$"?

Hey there! I've been diving into the world of Material-UI components and stumbled upon this interesting styling snippet: root: (0, _extends3.default)({}, theme.typography.subheading, { height: theme.spacing.unit * 3, boxSizing: 'content- ...

What is the best way to transform this into an HTML readable code?

While browsing through a template, I came across this code and I'm unsure of how to get it functioning. I've tried removing the comments, but unfortunately it doesn't seem to be working as expected. li.dropdown.navbar-cart ...

Inner box shadow obscured by a sibling div

I am facing an issue with a div that has an inner box shadow being covered by another div. I have tried using position: relative, but it did not solve the problem. Here is an example: CODE EXAMPLE .example-div{ background:#fff; color:#000; ma ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code: new Vue({ el: 'body', data:{ role: '', company: '', list:[], ...

What is the best way to trigger the ajax request with the same post parameter upon pressing the browser's back button?

Is there a way to remember the post parameters and resend an AJAX request when the browser back button is pressed? I have searched online and found a couple of methods: Using localsotrage or document.location.hash when the page unloads. Using cookie ...

Navigating from a web address to making an asynchronous request using history.js

As I work on a small website that features multiple pages with similar layouts, I often find that only the content within a specific div varies. The rest of the elements such as navigation and header remain consistent throughout. To address this, I have s ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...