Alert Content Using HTML DOM

Introduction

This tutorial provides an example of customising an alert popup using an HTML DOM <div> element to set the alert Content option.

The alert prompts the user to provide a name and value which are made available for use in the web application.

The alert is styled using CSS classes.

JavaScript

The web app page JavaScript.

Note | /*global swal*/ must be placed at the top of the script, before any code, and is not a comment; it allows validation to succeed when the swal open source library is being used. It could also be placed at the top of the web app's Global JavaScript and would then be effective for all pages in the app.

/*global swal*/

function test(){
  var msg = document.createElement("div"); //create DOM <div> element
  msg.innerHTML = '<input id="swal-input1" class="swal1-input" autofocus placeholder="Name"><input id="swal-input2" class="swal2-input" placeholder="Value"><button type="button" class="swal-button" onClick="closeSwal()">Cancel</button><button type="button" class="swal-button" onClick="settingValidation(this)">Save</button>';

  fsi.alert({
    title: "New Setting",
    content: msg, //alert uses DOM element as content
    closeOnClickOutside: false,
    buttons: false //suppress alert default 'Confirm' button
  });
}

function closeSwal() {
  swal.close();
  fsi.alert("You clicked Cancel");
}

function settingValidation(trigger) {
  //jQuery ".closest" and ".find" search DOM to find the parent and event 
  var name = $(trigger).closest('.swal-modal').find('#swal-input1').val();
  var value = $(trigger).closest('.swal-modal').find('#swal-input2').val();
  swal.close();
  fsi.alert(" You typed Name: " + name + "; Value: " + value);
}

HTML

The HTML content formatted for clarity (not suitable for copy/paste).

msg.innerHTML = '
<input id="swal-input1" class="swal1-input" autofocus placeholder="Name">
<input
id="swal-input2" class="swal2-input" placeholder="Value">
<button
type="button" class="swal-button" onClick="closeSwal()">Cancel</button>
<button
type="button" class="swal-button" onClick="settingValidation(this)">Save</button>
';

CSS

These CSS classes are added to the web app version Global CSS:

.swal1-input, .swal2-input {
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 20px;
  text-align: center;
}

.swal-button {
  margin-right: 5px;
  background-color: #4962B3;
}