A step-by-step guide on adding HTML content to a Bootstrap modal

Looking for assistance in appending HTML code within a Bootstrap modal.

Here is the HTML content:

<div class="modal fade" id="share12" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog">
      <div class="modal-content get_direction_modal_bg">
         <div class="text-right"><a class="fa fa-times white normal12" data-dismiss="modal"> close</a></div>
         <div class="modal-body">
            <p class="white text-center">Share this Event</p>
            <div class="share_list_popup">
               <ul>

           <li><a href="https://www.facebook.com/sharer/sharer.php?u=www.10times.com&title=Come join me at"+eventname+"on "+eventstartdate+", "+eventcityname+""></a></li>
                  <li><a href="http://www.linkedin.com/shareArticle?mini=true&utm_campaign=201308&url=http://10times.com/"+eventname+"&title=Come join me at  "+eventname+" on "+eventstartdate+","+eventcityname+".&utm_source=LinkedIn&source=LinkedIn
                     Come join me at "+eventname+" on "+eventstartdate+","+eventcityname+". Find event details at 10times.com/"+eventname+""></a>
                  </li>


               </ul>
            </div>
         </div>
      </div>
   </div>
</div> 
<a href="#" data-target="#share12" data-toggle="modal"><img src="images/share.png"></a>

And here's the accompanying Javascript code:

 var modal_event_name=document.getElementById("modal_event_name");
 var modal_event_startdate=document.getElementById("modal_event_name");
 var modal_city_name=document.getElementById("modal_event_name");
 $('#share12').modal('show');

The issue being faced:

  • The modal is not working as expected
  • Need guidance on displaying HTML content within a Bootstrap modal

View the JSFiddle example here

Answer №1

One of the convenient features of Bootstrap is its built-in methods for displaying and hiding modals. In Bootstrap 3, you can achieve this with the following code:

$("#pop").on("click", function() { 
  $('#imagemodal').modal('show');
  $('#imagemodal').on('shown.bs.modal', function() {
    $('#imagemodal').find('.modal-body').append('<p>insert some custom HTML content here</p>');
  });
});

Answer №2

It appears that you are attempting to directly use Javascript variables (eventname, eventstartdatae, eventcityname) within the HTML code. A better approach would be to construct the URL using Javascript and then utilize jQuery to set the <li> (list items) and <a href=""> (links):

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>

<body>

<div id="modal_event_name">My Event Name</div>
<div id="modal_event_startdate">My Event Start Date</div>
<div id="modal_city_name">My Event City Name</div>

<div class="modal fade" id="share12" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content get_direction_modal_bg">
      <div class="text-right"><a class="fa fa-times white normal12" data-dismiss="modal">close</a></div>
      <div class="modal-body">
        <p class="white text-center">Share this Event</p>
        <div class="share_list_popup">
          <ul>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>

<button onclick="showModal()">Show Modal</button>

<a href="#" data-target="#share12" data-toggle="modal">Show Modal From Link</a>

<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
  var eventname = document.getElementById("modal_event_name").textContent;
  var eventstartdate  = document.getElementById("modal_event_startdate").textContent;
  var eventcityname  = document.getElementById("modal_city_name").textContent;

  var facebookLink = "https://www.facebook.com/?" + eventname + "&" + eventstartdate + "&" + eventcityname

  var linkedinLink = "http://www.linkedin.com/?" + eventname + " & " + eventstartdate + "&" + eventcityname 

  $('.share_list_popup ul').append('<li><a href="' + facebookLink + '">Facebook</a></li>');
  $('.share_list_popup ul').append('<li><a href="' + linkedinLink + '">LinkedIn</a></li>');

  function showModal() {
    $('#share12').modal('show');
  }
</script>
</body>

</html>

View working example on JSFiddle

Answer №3

When it comes to manipulating modal data or any other element, there are various methods you can utilize. Bootstrap offers a range of options, which you can explore further here.

If you prefer using jQuery, here are some sample scenarios:

$("#pop").on("click", function() {

  //ref. to the modal
  var imgModal = $('#imagemodal');

  //Display the modal
  imgModal.modal('show');

  //reference to the body of the modal
  var imgModalBody = imgModal.find('.modal-body');

  //Replace the entire content of the body within the modal with this
  imgModalBody.html('<span style="color:red">This is appended directly from a string or variable</span><br/>');

  //Append a button to the modal body
  imgModalBody.append(' <button id="clickMe">Load content from hidden div</button><br/>');

  //Add a click event on the newly appended button
  imgModal.on("click", "#clickMe", function() {

    //Append text from the hidden div, myHiddenContent, onto the page 
    imgModalBody.append(' ' + $('#myHiddenContent').html());

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />

<a href="#" id="pop" data-target="#share12" data-toggle="modal">Open my modal</a>

<div id="myHiddenContent" style="display:none;">This is appended from html already on the page (hidden or not)</div>

<!-- Modal -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Image preview</h4>
      </div>
      <div class="modal-body">
        <img src="" id="imagepreview" style="width: 400px; height: 264px;" />
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Answer №4

Is it possible to create hyperlinks using a function?

For example:

<a href="javascript:executeFunction()">Link</a>

    function executeFunction()
    {
    var modal_event_name=document.getElementById("modal_event_name");
     var modal_event_startdate=document.getElementById("modal_event_name");
     var modal_city_name=document.getElementById("modal_event_name");

var url="path?modal_event_name="+modal_event_name+"&modal_event_startdate="+modal_event_startdate + "&modal_city_name="+modal_city_name;
window.open(url,""."");
    }

Does this approach work for you?

Answer №5

The modal functionality is operational with the provided code. Ensure that bootstrap js is included in the setup.

To incorporate variables, utilize the shown event of the modal.

var modal_event_name = "Event Name";
var modal_event_startdate = "10th July";
var modal_city_name = "SF"
$('#share12').modal('show');

$('#share12').on('shown.bs.modal', function () {
    if (!$(this).hasClass('social-links-added')) {
        $(this).addClass('social-links-added');
        var linkedin_url = "http://www.linkedin.com/shareArticle?mini=true&utm_campaign=201308&url=http://10times.com/" + modal_event_name + "&title=Come join me at  " + modal_event_name + " on " + modal_event_startdate + "," + modal_city_name + ".&utm_source=LinkedIn&source=LinkedIn Come join me at " + modal_event_name + " on " + modal_event_startdate + "," + modal_city_name + ". Find event details at 10times.com/" + modal_event_name;
        var facebook_url = "https://www.facebook.com/sharer/sharer.php?u=www.10times.com&title=Come join me at" + modal_event_name + "on " + modal_event_startdate + ", " + modal_city_name;
        $('.share_list_popup ul li:eq(0)').find('a').attr('href', facebook_url);
        $('.share_list_popup ul li:eq(1)').find('a').attr('href', linkedin_url);
        console.log(facebook_url);
        console.log(linkedin_url);
    }
});

Fiddle Link

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

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...

Issue with Vue router: history mode fails to work on the second level

I recently added a second router to my Vue.js project, specifically for a dashboard on my website. However, I encountered an issue where if I manually tried to access a specific route like "/admin/contact" or refreshed the page, I would receive a 404 error ...

Practical applications of flexible layouts in everyday life

I'm currently on the hunt for real-world examples of elastic layouts, specifically those based on using em's for widths. Surprisingly, I haven't been able to find much out there. If anyone knows of any examples, I would greatly appreciate it ...

Adding rows to a database can be done by utilizing a dynamic form that consists of both repeatable and unique fields

Here is my follow-up post addressing the issue I previously encountered. Initially, I erroneously used mysql instead of mysqli, but I have now made the necessary updates based on recommendations. I have a form that contains variable sets of fields (rangin ...

Tips for choosing every initial td element within a table

Hey there, I'm looking to style only the first <td> (specifically those with the text "label") in each row of a table. If we have a simple HTML structure like this: <table> <tr><td>label</td> <td>value</td> ...

Swapping out a View's content with the data fetched from an AJAX request

I'm currently developing a counselor portal using Asp.NET and Kendo UI controls within an MVC3 application. Within this system, there is a button labeled AddStudents which triggers the display of a partial view containing student information when clic ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

The width of the <ul> element does not properly accommodate the width of the <li> elements during the animation that updates the width of the <li>

I am currently working on implementing a typing animation in React. The li element has an animation that recursively changes its width from 0px to 100%. However, I have noticed that when the width of the li changes, the parent ul does not adjust its width ...

Fixing an $injector:unpr issue with Angular 1.6, MVC 4.6, and UI-Grid: A Step-by-Step Guide

Hello there! I'm currently in the process of developing a Web-App using Angular 1.6 / MVC 4.6 / E.F 6.0, and I've integrated UI-Grid into it from UI-Grid. The setup is running smoothly as intended. However, I've encountered an issue while t ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

What is the process for showcasing ImageGridFSProxy in an HTML file?

I am facing an issue with displaying images stored in MongoDB on a web page using Flask. The records have a binary field named "payload". class BinaryFile(mongo.Document): created_at = mongo.DateTimeField(default=datetime.datetime.now, required=True) ...

Is it possible for an onclick attribute to assign a function to document.getElementById without overwriting the existing value?

I want to create a numeric keypad in HTML with numbers 1-9, and I'm unsure if JavaScript can handle an onclick function for each key to show the number in the display div. What would be the most effective way to achieve this? <div id="display"> ...

Check for equality with an array of objects when reacting to changes

I have an input field and an array of objects. I want the object with a property named "airplaneCompany" to be displayed as I type. Each character should be checked, and if the object's "airplaneCompany" property starts with 'a', it should b ...

What methods can be employed to reduce additional background tasks when altering a state in a React component?

Trying out Code I experimented with creating a React exercise code that showcases a bus and its seats. Reserved seats are marked in red and cannot be selected, while the remaining seats can be chosen by clicking on them and selecting a gender from a popup ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

What is the best way to ensure that a div takes up as much vertical space as possible within its

Check out my design at https://jsfiddle.net/49hsztuh/ Take a look at the code snippet below: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <link rel="stylesheet" type="text/c ...

What is the proper way to invoke requestAnimFrame on a method within an object?

Imagine a scenario where the following object exists: function Foo(value){ this.bar = value; this.update(); } Foo.prototype.update = function(){ console.log(this.bar); this.bar++; requestAnimationFrame(this.update); } Foo.prototype.set ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...