Tips for accessing information from a FOR loop within DIV tags

Let's explore the following code snippet:

Here is the HTML generated:

            <!DOCTYPE html>
            <html lang="en">

            <head>
                  <meta charset="utf-8">
                <title>Website TEST</title>
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <meta name="description" content="">
                <link rel="stylesheet"                 href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
            </head>

            <body>

              <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
              <a class="navbar-brand" href="#">Ww1</a>
              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarWw1" aria-controls="navbarWw1" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
              </button>

                              <div class="collapse navbar-collapse" id="navbarWw1">
                <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                  <li class="nav-item active">
                    <a class="nav-link" href="/">Home <span class="sr-only">(current)                </span>                </a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="map">Map</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="about">About</a>
                  </li>
                </ul>
                <form class="form-inline my-2 my-lg-0">
                  <input class="form-control mr-sm-2" id="myInput" type="search" onkeyup="myFunction()" placeholder="Find your next memories!">
                </form>
                              </div>
                            </nav>

              <div class="container-fluid" id="networdapp" style="display:none;">
                 <div class="row" >
                    <div v-for="result in results" class="col-sm-6" >
                      <div class="card m-3 h-240  bg-light" >
         <div class="card-header text-center" > {{ result.title }} </div>
           <div class="card-body" style="height:200px" >
             <p class="card-text" v-html="result.prevDesc"></p>
           </div>
             <div class="card-footer bg-transparent border-info">
               <a href="/details" class="btn btn-info" onclick="getData();">Details</a>
             </div>
         </div>
                      </div>
                  </div>
            </div>
              </body>

              <script src="https://unpkg.com/vue"></script>
              <script src="https://unpkg.com/axios/dist/axios.min.js">                </script>

              <script>

            function myFunction() {
                var input , filter , OK = false ;
                input = document.getElementById("myInput");
                filter = input.value.toUpperCase();
            if(filter.length > 0 ) {
            document.getElementById("networdapp").style.display = "";
            $( ".col-sm-6" ).each(function( index ) {
            if ($(this).text().toUpperCase().indexOf(filter) > -1){
            this.style.display="";
            }else{
            this.style.display="none";
            }
            });
            }
            else{
            document.getElementById("networdapp").style.display = "none";
            }
            }


              </script>

              <script type="text/javascript">
              const vm = new Vue({
                el: '#networdapp',
                data: {
                  results:[]
                 },
                 mounted() {
                   axios.get('/getJson')
                 .then(response => {
                    this.results = response.data;
                 })
                 .catch( e => {
                   console.log(e);
                 });
                }
              });

            function getData() {
            window.alert($(this).parents("#networdapp").find(".card-header.text-center").text());
            window.alert(console.log( $(this).closest(".row").find(".card-header.text-center").html() ));
            }

              </script>

            </html>

In the above code, there is a

<div class="container-fluid" id="networdapp">
where multiple divs are generated using
<div v-for="result in results" class="col-sm-6" >
. The goal is to click on the "Details" button of one of these generated divs and retrieve the data from {{ result.title }} (from the
<div class="card-header text-center">
) and use it for another template called x.ejs.

The technologies used include EJS, Vue.JS, some jQuery, and libraries like Axios.

If you encounter any issues while trying to retrieve the data from a random generated div, ensure that your script is targeting the correct elements and handling events appropriately.

Good luck with your implementation!

Answer №1

When working with Vue.js, you can enhance your code by replacing onclick with @click. Pass result and $event as parameters like this:

...
<a href="/details" class="btn btn-info" @click="getData(result,$event)">Details</a> 
...

In your methods section, call the function in this way:

const vm = new Vue({
  el: '#networdapp',
  data: {
    results:[]
  },
  methods:{
    getData: function(result, event) {
      // Perform actions with result and event
      console.log(event.target.outerHTML);
      // Access attributes of the target anchor element (<a></a>) here       
     }
   }
   ...
 }

You can also remove the unnecessary function getData(){...}

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

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Navigating with Angular Material and md-nav-bar for efficient routing

Currently, I am delving into Angular and have opted to utilize the Angular Material library for my initial application. After tweaking some basic code borrowed from this source, which I adjusted to suit my requirements, I encountered difficulties with rout ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

Disabling a text area or mat-form-field within the same HTML file in Angular 9

Currently, I am working with Angular 9 and angular Material Reactive Forms. My goal is to disable certain fields without relying on the disabled status within formControl in the TypeScript file. Instead, I want to achieve this solely through HTML. Here is ...

The Angular Sortable Containment feature ensures that items cannot be dropped outside of

I am experiencing an issue with a horizontal sortable Angular list where the containment option is not functioning properly, causing the dragged item to not be dropped. Take a look at the sortable list below without a containment option - you may notice t ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

Disappearing act: Ionic tabs mysteriously disappear when the back button

Whenever I navigate in my ionic app, I notice that the tabs-bar disappears when I go to different pages and then return to the tabs. See Demo Code tab1 Here is a sample link to navigate to other pages: <ion-label routerDirection="forward" [routerLi ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Update location when visibility changes

Looking for a way to automatically refresh an HTML page when a specific div becomes visible, but seems like I am missing something. There is a JavaScript code, divslide.js, that changes the display style of the div from none to inline at predetermined time ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...

Transmit specific elements from an array to another array exclusively with Javascript

I have some data stored in a JSON array like this: source=[{"OperationName":"All","PrivilegeName":"Roles CRUD"}, {"OperationName":"Read","PrivilegeName":"Roles Read Delete"}, {"OperationName":"Delete","PrivilegeName":"Roles Read Delete"}, ...

Aligning Elements in the CSS Bootstrap Grid

Struggling to achieve perfect center alignment of an HTML element using the Bootstrap grid framework. Here's the current code: <div id="rentals" class="container pb-4"> <div class="row pt-5 mt-5 mb-4"> ...

npm encountered an error while trying to install selenium-webdriver using the npm install command

My operating system is Windows Server 2008 R2 EE and I have the npm package manager installed. I am attempting to install the Selenium Webdriver package using the command below. Command: npm install selenium-webdriver However, when running this comma ...

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Unable to specify a particular <div> for fetching data using jQuery AJAX in ASP.NET

While working on the following Javascript code, I encountered an issue where the text specified inside the CommentItem div I am appending is not displaying. However, my main concern revolves around targeting ContainerPh which is located above the txtCommen ...

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

Setting the background color in the navbar of a Laravel application

I'm having trouble changing the color of my navbar to blue in certain parts. I've tried using background: lightblue;, but for some reason, two sections remain white. How can I make them completely blue? (see screenshot below) Any help would be ap ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...