L84
L84

Reputation: 46298

Check contains of an alert using jQuery, then run function based on contents

I have a webform that has several required field. When I submit the form, my CMS automatically includes some JS Validation to check. Their validation looks something like this:

function checkWholeForm88517(theForm) {
   var why = "";
   if (theForm.CAT_Custom_1) why += isEmpty(theForm.CAT_Custom_1.value, "First Name");
   if (theForm.CAT_Custom_2) why += isEmpty(theForm.CAT_Custom_2.value, "Last Name");
   if (theForm.CAT_Custom_3) why += isEmpty(theForm.CAT_Custom_3.value, "Email Address");
   //etc.

   if (why != "") {
      alert(why);
      return false;
   }
}

When an alert pops up it will contain text like so:

- Please enter First Name
- Please enter Last Name
- Please enter Email Address

What I would like to do is run an if statement to see if the alert contains - Please enter First Name and if so, do something.

I tried doing this:

window.alert = function(msg) {

   if ($(this).is(':contains("- Please enter First Name")')) {
       $( ".error-msg" ).append('My Message...');
   }

}

Of course, this isn't working as I'm not exactly sure how to target the msg of the alert and check to see if it contains the text.

How would I do this?

Upvotes: 0

Views: 212

Answers (2)

Quentin
Quentin

Reputation: 943100

You need to treat the argument as a string and not the context object (window) as a DOM object.

if (msg.indexOf("some_substring") > 1)

Upvotes: 4

Josh Crozier
Josh Crozier

Reputation: 240858

In your example, this likely refers to the window object. You need to test whether the message argument contains the string:

window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
}

Quentin already said that, but I wanted to mention that if you want to maintain or restore the original .alert() behavior, you can save a reference to the function:

var _defaultAlert = window.alert;
window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
  _defaultAlert.apply(window, arguments);
}

Upvotes: 1

Related Questions