L. Becker
L. Becker

Reputation: 59

How do you pass looping values to a Bootstrap modal?

Preface: I've looked at answers about passing variables into a Bootstrap modal. They do not seem to address my problem.

I'm iterating over a JSON object which has an image URL and an array of comments about that image like so--

[{
    URL:"www.imageurl.com/image1.jpg", 
    COMMENTS:[
            {comment: "Hello", by: "Jane"}, 
            {comment: "World", by: "John"}
    ]
},{
    URL:"www.imageurl.com/image2.jpg", 
    COMMENTS:[
            {comment: "Ruby", by: "Ann"}, 
            {comment: "Is Better", by: "Luke"}
    ]
}]

This is a Node.js app so I'm writing in Jade, but for the sake of clarity, I'll refer to HTML. So I'm iterating through the JSON object (for image in images) and for each image, I'm creating an <img> tag wrapped with an <a> tag that opens the modal. Inside the modal, I would like to display the appropriate comments and author for the clicked image. So, if "image in images" is referring to image1.jpg, the modal should display Hello - by Jane, World - by John.

My problem is that I'm in a loop and I need to pass into the modal the correct image object. How do I do this?

Upvotes: 0

Views: 833

Answers (1)

Laura
Laura

Reputation: 3383

You will need to add the comments to the <img> or <a> somehow, the easiest way will probably be using data-* attributes.
Stringify the JSON and put it in a data-comments attribute on the <img>:

<img data-comments='[{"comment":"Hello","by":"Jane"},{"comment":"World","by":"John"}]'>

Then in your click event (or use the show.bs.modal event like in the docs) get the comments of the target element:

$('.link-that-opens-the-modal').on('click', function(event) {
    event.preventDefault();
    var clickedLink = $(event.currentTarget); 
    var currentImage = clickedLink.children('img'); // use .find() if necessary

    // JSON should be automatically converted to an Object
    var comments = currentImage.data('comments'); 

    // append image and comments to modal however you want and show modal
    // ...
});

(you could also do this without the link by the way and put the click handler on the <img> if you don't need the link otherwise)

Upvotes: 1

Related Questions