Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id.

Here is the code snippet I've been working on. Unfortunately, it doesn't work as intended because the modal appears behind the black filter and only retrieves the first id on button click.

example1 example

    echo '<a href='.get_permalink($product_id).'?sku='.$product->get_sku().'><button class="second_content">en savoir plus '. $product->get_sku().'</button></a><button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>';

   echo '    <div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">'.$product->get_sku().'
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>';

Answer №1

If you want to dynamically set the SKU using JavaScript when the modal is triggered, I suggest the following approach:

$('#myModal').on('shown.bs.modal', function (e) {
    var sku = e.relatedTarget.attr('id');
    // Alternatively, you could extract the SKU from the href attribute in your URL
    $('#skuId').html(sku)
})

Next, adjust your HTML code as follows:

echo '<a href='.get_permalink($product_id).'?sku='.$product->get_sku().' id='.$product->get_sku().'><button class="second_content">Learn more about '. $product->get_sku().'</button></a><button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>';

Update your modal structure like this:

echo '
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
    <div class="modal-content"><div id="skuId">[to be set on show]</div>
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>';

Keep in mind that while I have not tested this exact implementation, it should work with a few tweaks.

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

React and Mui are experiencing a peculiar issue where a background is mysteriously missing from a component in a specific location

Exploring React 16 and functional components with hooks Discussing Mui 4 framework Adding a background pattern to multiple login pages seems simple, right? Here is an example of a login page component: return ( <Box width={1} height={1}> ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...

Tips for minimizing excess white space in Shiny applications

Encountering an issue with plot output in Shiny. When using standard ggplots, the output is correct without any extra white margins. However, when utilizing the "ggmap" package (which also produces ggplot-type outputs), white margins suddenly appear. (Ple ...

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

Splitting a loading button within post.map() in React for like/dislike functionality

I'm currently working on implementing a like/dislike feature in React. The issue I've run into is that when I try to like or dislike a post, the like/dislike buttons on all other posts are stuck in a loading state. This means that while I'm ...

The font in my Next.js / Tailwind CSS project starts off bold, but unexpectedly switches back to its original style

I recently integrated the Raleway font into my minimalist Next.js application with Tailwind CSS. I downloaded the font family in .ttf format and converted it to .woff2, but I'm having trouble changing the font weight using custom classes like font-bol ...

Steps for transferring an `<li>` element from one `<ul>` to another

<ul id="List"> <li class="li">1</li> <li class="li">2</li> </ul> <ul id="List2"></ul> const items = document.querySelectorAll(".li"); for(var i = 0; i < ...

Why is the v-for directive malfunctioning and am I correctly displaying it in the template?

I'm new to working with Vuejs and recently created a mock dataset using JSON. The JSON file consists of an array containing 3 objects. Although console.log shows that Axios.get(URL) is fetching the data correctly, the v-for directive doesn't seem ...

Creating custom designs for Material UI components

Although not a major issue, there is something that bothers me. I am currently using react, typescript, and css modules along with . The problem arises when styling material ui components as I find myself needing to use !important quite frequently. Is th ...

Label positioning for checkboxes

Is there a way to display the checkbox label before the actual checkbox without using the "for" attribute in the label tag? I need to maintain the specific combination of the checkbox and label elements and cannot use nested labels or place other HTML elem ...

Adding div elements using checkbox switch

In this code snippet, my aim is to display costs based on checkbox selection and generate corresponding totals in the bottom row when the checkboxes are toggled. The goal is to allow users to choose relevant items and have the total cost calculated accordi ...

Create a random number on the server every X interval

Context I have developed a Node.js application that generates a random number every 6 seconds and exposes it through an API. To maintain separation of concerns, I decided to encapsulate the number generation logic in a function called numberGen, stored i ...

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

Node Express JS: Efficiently handling multiple fetch responses before sending data to client

My goal is to call an API that only accepts one animal name at a time, but I receive the names of multiple animals in a query separated by commas. To achieve this, I plan to call the API once for each animal, push the JSON data into an array, and then resp ...

Break up in the middle of a sentence: Material UI

Currently facing an issue where my sentences break in the middle. Working with Material UI requires manual styling of different components like MUI. The problem I'm encountering can be seen below. I tried removing the display: flex, but then the squar ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...

What is the best way to update the value of a preact signal from a different component?

export const clicked = signal(false); const handleClickDay = (date) => { const day = date.getDate().toString().padStart(2,'0') const month = (date.getMonth()+1).toString().padStart(2,'0') const year = da ...

Is there a distinction between em and percentage measurements and do their defaults have specified definitions?

Both em and percentage are defined in relation to other elements or properties. For example, with text-indent, it is related to the width of the paragraph, while with font size, it is related to the browser's default size. The question arises - wh ...

Ensuring promise resolutions in a chain using Angular JavaScript before delivering a final result

I have a scenario in Angular where I am using a chain of promises and I want to ensure that a value is returned at the end of the chain: this.calculateeventsattended = function(username) { var Attendees = Parse.Object.extend("Attendees"); var User = ...