Torbjorn Zetterlund

Mon 11 2016

Passing data from a list to a bootstrap modal

by bernt & torsten

I had a little problem the other day, I was building this list of feeds for an application I product manage. The web application uses PHP and bootstrap, so the design is based on bootstrap buttons when clicked, opens a modal from which the next action is taken.

The list of feeds looks like this

Each feed has a unique feed id, this feed id is used in the modal to send an Ajax call to the backend which takes an action to either enable or disable a feed on the list. When a feed is disabled, it is not used when the crontab calls the function to update feeds and vice versa.

When clicking on the button Suspend/Activate – a model will open up like this.

popup modal

From the drop-down list in the modal, the user can select the action to take, when clicking confirm an Ajax call is made to the backend to update the feed check time.

In the Ajax call, the feed id is sent to the backend to find the right feed id in a table. The problem I came across initially was that the feed id that was in the modal – was always the same feed id for any button I pressed. So what do I have to do to get the button to pass the feed_id to the modal so it can be sent in the form action to the backend?

How to pass the data to the parameters

<button type="button" class="btn btn-warning feed-id" data-toggle="modal" data-target="#statusModal" data-id="<? echo $feed['id'] ?>"><?php echo __('feeds:feedsuspend') ?>

In the button, I added in the class parameter feed_id, in the modal I added a hidden input

<input id="feed_id" name="cid" type="hidden" value="" />

In my javascript, I added this code

$(document).ready(function () {
$('body').on('click', '.feed-id',function(){
document.getElementById("feed_id").value = $(this).attr('data-id');

The javascript looks for feed_id and scans the dom for it, and when it finds it we request the data_id value to be passed and inserted in the value field in the hidden input. When the “confirm” button is clicked on the modal, the input value is passed to the function that sends the request to the backend.

That’s all to pass data to a modal. Let me know what you think below.