Discover the seamless integration of v-for with SweetAlert2 for dynamic HTML output

I'm attempting to display the following template in an alert using vue-sweetalert2:

<input v-model="name" class="swal2-input">

<select v-model="parent" name="parent" class="form-control">
  <option v-for="category in categories" v-bind:value="category.id">
    {{category.name}}
  </option>
</select>

While I have no issue with a regular template, I am unsure how to implement this in SweetAlert2.

I attempted the following code:

this.$swal({
  text: 'edit child',
  html:
   '<input v-model="name" class="swal2-input">' +
   `<select v-model="parent" name="parent" class="form-control">
      <option value="">nothing</option>
      <option v-for="category in categories" v-bind:value="category.id">
        {{category.name}}
      </option>
    </select>`,
  showCancelButton: true,
  confirmButtonText: 'edit',
  cancelButtonText: 'cancel',
  showCloseButton: true,
})

Unfortunately, it displays nothing.

Answer №1

When passing HTML to SweetAlert2 that is not handled by Vue, the template mechanisms such as v-for and v-model would not be accessible. This means you will need to manually create the template using JavaScript. Here's how:

html: `<input v-model="name" class="swal2-input">
<select v-model="parent" name="parent" class="form-control">
  <option v-for="category in categories" v-bind:value="category.id">{{category.name}}</option> ...`

You can replace the above code with this:

html: `<input id="my-input" value="${this.name}" class="swal2-input">
<select id="my-select" value="${this.parent}" name="parent" class="form-control">
  ${this.categories.map(cat => `<option value="${cat.id}">${cat.name}</option>`)} ...`

It's important to note that IDs were added to the <input> and <select> elements so that we can retrieve their values before confirming the alert:

const {value} = this.$swal({
  preConfirm: () => [
    document.getElementById("my-input").value,
    document.getElementById("my-select").value
  ]
});
console.log(value[0]); // value of my-input
console.log(value[1]); // value of my-select

Check out the demo here.

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

Issue encountered when attempting to add multiple JavaScript functions through Greasemonkey using unsafeWindow

One issue that arises is that the functions are unable to recognize each other. For example: unsafeWindow.helloworld = function() { alert('Hello world!'); helloworld2(); // this fails with an error indicating it does not exist } unsa ...

Retrieve the JSON object with an AJAX request that contains three arrays, then transfer these arrays to JavaScript

A web page I designed generates the following content: <script> var JSONObject = { "groups":['1210103','1210103','1210103','1210405'], "prices":['279,00','399,00',&ap ...

Notification Popup Occurs in Quadruplicate

My question exceeds the limitations of the title, so I'll elaborate here. I am developing an app that can write and read a NDEF message on/from NFC cards when detected by a phone. The issue is that everything in the code seems to repeat itself four ti ...

Leveraging AJAX Response for Ending a Parallel Query

Imagine initiating an AJAX HTTP Request through jQuery to a PHP script on the back-end that interacts with a MySQL server. What if, during this request, you want to create a new one and halt the existing process on the server? The file front-end.php has t ...

The component 'AppComponent' cannot access the property 'results'

Having some trouble accessing the results field from a json response. The error message reads, Property 'results' does not exist on type 'AppComponent'. import { Component } from '@angular/core'; // Import `HttpClient` impor ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

Verification checkbox in Html5 is mandatory

I have created an input checkbox that contains array values, resulting in multiple rows being generated in a table. However, the issue I am facing is that all checkboxes need to be checked in order to submit the form. This means I cannot submit the form un ...

Generating numerous checkboxes dynamically

Seeking assistance with a jQuery function that dynamically generates or clones checkboxes. The challenge is to display the sub_item checkbox when the main_item checkbox is checked. For a demonstration, you can visit this DEMO Jquery $('#btnAdd' ...

Troubleshooting Node.JS body parsing problems

I am struggling to transmit data from one machine to another using node.js. I am facing some challenges with getting the parser to work properly. Below is my client and server code: Client.JS var request = require('request'); request.post( ...

Tips for interacting with Vue js buttons on JSP pages with Selenium WebDriver in Java

Having trouble locating elements rendered by vue.js within a JSP page. While I can find elements using xpath in normal JSP pages, those rendered by Vue.js remain elusive. For example, my JSP page includes: <div id="fileUploadDiv" style="display: flex; ...

Guide on using a pipe feature with varying arguments when the main function is called

I am delving into functional programming for the first time and have a query regarding using pipes. Imagine I have this particular function: const updateArray = R.curry((index, value, array) => Object.assign([], array, {[index]: v ...

Importing files dynamically in JavaScript

Currently, I have a requirement to dynamically import a markup file, extract a portion of the file, assign it to a variable, and then display the result in my React application: import('../changelog.md').then(...) I have attempted to achieve th ...

Having trouble initializing and retrieving an array from the controller in AngularJS

I tried to set up and retrieve the array values from the controller. Check out the fiddle here. var app = angular.module('carApp', []); app.controller('carAppCtrlr', function ($scope) { $scope.vehicles = [{ type: ' ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...

Sorting elements of an array by symbol using the sort() method

Can someone assist me with sorting the element cinema in array arr by symbol unicode (the output should be "aceinm")? I am aware that I need to use the sort() method in this case. However, I am unsure of how to apply the sort method to an array element. A ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

The issue with the Woocommerce quantity increment buttons not functioning properly persists after an AJAX refresh, and the automatic load feature only activates after two

I've hit a brick wall with this particular issue. Many people have suggested solutions, but none seem to be effective for me. My situation probably resonates with quite a few individuals: I decided to customize the WooCommerce quantity input (/global ...

Populate a div using an HTML file with the help of AJAX

In my main HTML file, there is a div element: <div id="content"></div> Additionally, I have two other HTML files: login.html and signup.html. Furthermore, there is a navigation bar located at the top of the page. I am curious to know if it i ...