Bodrov
Bodrov

Reputation: 867

Clicking on div and appending the value of that div into it

I have some Category Titles that are each being appended into their own div. Clicking on any of the divs opens a modal and the plan is to append that Category's Title into the modal as well.

I originally had the title .append in a for loop, but each of the category titles was appended next to each other. It must've been due to the loop but moving it out of the loop doesn't load the category divs.

I then inserted an .eq(i).append into the statement but it only displayed the first Category Title (in this case it's "Animals").

Is there a way to append the Category Title into whichever modal it was clicked on? Would I be able to get the index of that Category Title and append it, similar to what I had originally?

JS snippet:

let _library,
    _categories;

getCategories(){ 
    return _categories;
}

loadCategories(){
    let categs = _categories

    let htmlElems = "";
      for (var i = 0; i < categs.length; i++) {
           htmlElems += "<div class='cat-box cat-num-" + i + "'data-target='#modal-id' data-toggle='modal'>" + categs[i].Title + "</div>";
           $(".modal-title").eq(i).append(categs[i].Title); // ---------- //
      }

     let container = document.querySelector("div.top-training");
     container.innerHTML = htmlElems;
     console.log(container);

}

index.js:

$(document).on("click", '.cat-box', function(val) {
    console.log('.cat-box clicked')
    let cat  = $(this).data('category'),
        desc = $(this).find("span").last().text();

// irrelevant code

Modal:

<div class="modal" id="modal-id" role="dialog">
<!-- ...etc -->
<div class="modal-title" id="exampleModalLabel"></div>

Upvotes: 0

Views: 72

Answers (1)

Saji
Saji

Reputation: 1394

You can try below approach to fix this issue.

First, add data attribute data-title to the element .cat-box to keep title data.

htmlElems += "<div class='cat-box cat-num-" + i + "'data-target='#modal-id' data-toggle='modal' data-title='"+ categs[i].Title +"'>" + categs[i].Title + "</div>";

When modal is open read the title data and put inside the .modal-title and make it empty on close.

$(document).find('#modal-id').off('shown.bs.modal').on('shown.bs.modal', function (e) {
    $(document).find('.modal-title').html( $(e.relatedTarget).data('title'));
}).on('hidden.bs.modal', function (e) {
    $(document).find('.modal-title').html('');
});

You can see detailed example from bootstrap site

Upvotes: 1

Related Questions