Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically.

Here is the HTML snippet:

<div
  class="alert alert-success alert-dismissible fade show"
  role="alert"
  id="accepted-meal-alert">
  <button type="button" class="close">&times;</button>
  <p>Genial que te haya gustado la idea!</p>
</div>

The CSS code:

#accepted-meal-alert {
  display: none;
}

And the JavaScript logic. I am using jQuery to toggle the visibility of the div:

function acceptOrGetAnotherMeal(acceptOrReject) {
  if (acceptOrReject == 'accept-btn') {
    showMealAccepted();
  } else {
    const alternativeTextPrefix = 'Entonces pidamos';
    let mealType = $("input[name='categorias']:checked").val();
    console.log(`mealType: ${mealType}`);
    getFromEndpoint(mealType, alternativeTextPrefix);
  }
}

function showMealAccepted() {
  console.log('showMealAccepted');
  $('#accepted-meal-alert').show();             // `toggle` didn't work as well.
  // $('#accepted-meal-alert').css({
  //   display: 'block',
  // });
  $('#accept-btn').prop('disabled', true);
  $('#reject-btn').prop('disabled', true);
}

$(document).ready(function () {
  $('.categorias').click(function () {
    let endpoint = $(this).attr('id');
    getFromEndpoint(endpoint, defaultTextPrefix);
  });
  $('.accept-reject-btn').click(function () {
    let acceptOrReject = $(this).attr('id');
    console.log('Clicked categories with value: ' + acceptOrReject);
    acceptOrGetAnotherMeal(acceptOrReject);
  });
  $('.alert .close').click(function (e) {
    $(this).parent().hide();
  });
});

If it matters, these files are being served from a public folder in Sinatra.

Answer №1

Before proceeding, ensure that the JavaScript is loading correctly by adding a log statement and verifying if the '.accept-reject-btn' is triggering the click event.

Consider testing the following JavaScript code:

function acceptOrGetAnotherMeal(acceptOrReject) {
    if (acceptOrReject == 'accept-btn') {
        console.log( 'Meal accepted.' );
        showMealAccepted();
    } else {
        console.log( 'Meal rejected!' );
        alert( 'Meal rejected!' );
    }
    $('#accept-btn').prop('disabled', true);
    $('#reject-btn').prop('disabled', true);
}

function showMealAccepted() {
    console.log( 'showing meal accepted...' );

    $('#accepted-meal-alert').show();
}

$(document).ready(function () {
    $( document.body ).on( 'click', '.accept-reject-btn', function () {
        console.log( 'Clicked accept-reject button...' );

        let acceptOrReject = $(this).attr('id');
        acceptOrGetAnotherMeal(acceptOrReject);
    });
    $( document.body ).on( 'click', '.alert .close', function (e) {
        $(this).parent().hide();
    });
   $( document.body ).on( 'click', '.reset', function() {
        $('#accept-btn').prop('disabled', false);
        $('#reject-btn').prop('disabled', false);
        $('#accepted-meal-alert').hide();
        console.clear();
    });
});
#accepted-meal-alert {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div
  class="alert alert-success alert-dismissible fade show"
  role="alert"
  id="accepted-meal-alert">
  <button type="button" class="close">&times;</button>
  <p>Great to see you liked the idea!</p>
</div>

<button class="accept-reject-btn" id="accept-btn">Accept</button>
<button class="accept-reject-btn" id="reject-btn">Reject</button>
<button class="reset">Reset</button>

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

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Retrieving data from a dynamic table by utilizing variables

After some testing, I came across a way to select rows from a dynamic table within the range of 2 and 5: var limitTable = $(table).find('tr:gt(2):lt(5)'); However, attempting to use variables in place of hardcoded values doesn't seem to wo ...

The React Material UI table is having trouble stretching to fill the space

Currently, I am experimenting with developing my own virtualization technique using a different approach than react-virtualized. However, I am encountering difficulties when it comes to styling. I have come across an issue where the material table in the ...

The relevance of this concept in the classroom setting and within the setTimeout function is integral to

Having recently started learning JS, I have gone through various answers on the context of "this" with classes and setTimeout(), but I am facing a specific issue. I am struggling to understand the thought process or mental model behind the following code ...

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

Adding TypeScript types to an array within a function parameter: A step-by-step guide

Having some trouble defining the array type: The code below is functioning perfectly: const messageCustomStyles: Array<keyof IAlertMessage> = [ 'font', 'margin', 'padding' ]; r ...

How do I verify response values in Postman tests when the input parameter may be empty and can have multiple possible values?

In my program, there is an input parameter known as IsFruit that can have a value of either 0 or 1. If IsFruit is set to 0, the response should return fruits with a FruitsYN value of N. Similarly, if it is set to 1, FruitsYN should be Y. In cases where I ...

Difficulty in retrieving attribute information from an image - JQuery

I have been attempting to extract the attribute from images that I have obtained from a collection of ul-based image galleries using the clone function. Here is the Ul Tag I am trying to clone: <ul class="bannerscollection_zoominout_list"> ...

Switch all occurrences of https URLs with <a> using the stencil technology

I am encountering an issue with replacing the answer retrieved from an API and formatting it correctly answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com &bso ...

Placing a div in the corner of an image

Is there a way to position a meta-data div in the corner of every post image, even with different image sizes? For example: This is what I currently have in my loop: <div id="images"> <?php wp_get_attachment_image(); ?> </div> < ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...

Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after ...

JavaScript's Circular Output

I am currently developing a calculator and I want it to round the results to approximately 5 decimal places. Below is the JavaScript code snippet I have written to take input and generate output: <div class="input"> Price paid per s ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

Any ideas on how I can enable rotation of SVG images within a Bootstrap 4 Accordion card with just a click?

I'm working on a Bootstrap 4 accordion card that has an SVG arrow image in each header. I am trying to make the arrow rotate 180 degrees when the header is open, and return to its initial state when it is closed or another header is opened. Currently, ...

What might be the reason for my react-bootstrap modal not applying any styling?

I have two projects, one created by following a tutorial series and the other created independently later on, aiming to replicate the first project. I have narrowed down my issue to a basic comparison of index.js in both projects. This code is an edited v ...

Vuetify - Best practices for vertically aligning rows in a v-treeview component

Just getting started with Vue js, so pardon me if this is a silly question. I've scoured the internet and can't seem to find a solution. I'm working on a v-treeview displaying a folder structure, with descriptions of each folder in a separa ...

Exploring data elements in a Javascript array

Is there a way to use Javascript or jQuery to address the individual employee number, tasks, and sites in the following JSON array? $.each(mySchedule, function(i, obj) { console.log(obj.employees); }); var mySchedule = { "schedule": { "empl ...

Creating a 2D image of a Three.js scene in JPG format: Is it possible?

I am working with a three.js scene that includes rendering a 3D cube. The code snippet for the scene setup is shown below: var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHe ...