GithubHelp home page GithubHelp logo

codedance / jquery.areyousure Goto Github PK

View Code? Open in Web Editor NEW
508.0 508.0 145.0 98 KB

A light-weight jQuery "dirty forms" Plugin - it monitors html forms and alerts users to unsaved changes if they attempt to close the browser or navigate away from the page. (Are you sure?)

JavaScript 99.14% HTML 0.86%

jquery.areyousure's People

Contributors

albinsunnanbo avatar apassant avatar atefbb avatar bjeanes avatar bryant1410 avatar codedance avatar jonegerton avatar nicolas-brousse avatar scadoodles avatar tclift avatar valgen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.areyousure's Issues

Fire off dirty event

Is there a way to specifically fire off a dirty event?

I have a calendar widget that when it's value is changed I add the 'dirty' class to the form. Works great, but I also have some save buttons that are disabled unless the form is dirty. I'm disabling/enabling the buttons via the dirty/clean events being fired, which don't get fired (obviously) when I add the 'dirty' class to the form.

So wondering if I can fire off the dirty/clean events from within another function.

Using AreYouSure with jQuery Chosen

Hello,

Chosen is similar to Select2. I'm using it to improve the UI/UX of multiple selects. I can't get Chosen to play nicely with AreYouSure. Here is what I'm seing in the console:

Uncaught TypeError: Cannot read property 'toString' of null 

Therefore, to validate the rest of the form, I'm ignoring the fields on which Chosen is applied.

Could you please let me know what I should do? I tried both rescan & reinitialize.

Here is my implementation of Chosen (simplified):

if (jQuery().chosen) {

    $('.chosen-select').each(function () {

        $(this).chosen().change(function () {

            // doing stuff here

        });
    });
}

Include concrete methods as well as triggers

Would be nice to have concrete methods to call, as well as the triggers for actions. For example instead of

$("form").trigger("rescan.areYouSure");

we'd have something along the lines of:

$("form").areYouSure.rescan();

This would give IDEs with intellisense something to go off and help avoid bugs when coding. It would also improve compatibility with things like TypeScript.

Incidentally, I added areYouSure to DefinitelyTyped here.

Add a custom check

Hi there!

Great plugin.
Is there a way to customize the check of are you sure?

What I want :

if form is dirty
    send an alert
if form isn't dirty
    if custom function return true
        send an alert

Thanks!

Are You Sure Plugin Is not working properly

Suppose you have a page called FirstPage with one date field.
After page loaded sucessfully , populated value of this date filed is 03/06/2013 .

Now you click the SecondPage Link without changing any values in FirstPage , but till the popup is comming .

Solution : We have Fixed this issue by changing the jquery.are-you-sure.js file, below is the change code
-------------------------------------------------OLD-----------------------------------------------------------------
var checkForm = function(evt) {
var isFieldDirty = function($field) {
return (getValue($field) != $field.data('ays-orig'));

};

-------------------------------------------------NEW-----------------------------------------------------------------
var checkForm = function (evt) {
var isFieldDirty = function ($field) {

            if ((getValue($field).match(/^\d\d?\/\d\d?\/\d\d\d\d$/)) && ($field.data('ays-orig').match(/^\d\d?\/\d\d?\/\d\d\d\d$/))) {
                var getDate = getValue($field).split('/');
                var orgDate = $field.data('ays-orig').split('/');
                getDate = parseInt(getDate[0], 10) + "/" + parseInt(getDate[1], 10) + "/" + parseInt(getDate[2], 10);
                orgDate = parseInt(orgDate[0], 10) + "/" + parseInt(orgDate[1], 10) + "/" + parseInt(orgDate[2], 10);                   
                return (getDate != orgDate);
            }
            else {                    
                return (getValue($field) != $field.data('ays-orig'));
            }
        };

How to trigger Are You Sure form check in code?

Hi,

We have menu on top layout and content form below. Whenever the user clicks on menu link, we are replacing the content form using Ajax. We would like to do dirty data check on menu click if the user is navigating to other page and fire the alert. I guess here beforeunload event won't be fired.

How to fire the dirty data check in the code and fire the alert?

Customization of confirm popup when fields are dirty.

Is there any way to customize the confirm popup when fields are dirty and user is moving to other page or refreshing it.

Currently it shows browser inbuilt confirm box.

Please guide us for same.Is there really any options to customize this or not ??

Safari Mobile - how to display prompt message and prevent refreshing page without clicking any links

I'm trying to show the prompt message and prevent refreshing page if user's trying to refresh the page.

I would like the message can be shown if user hasn't click on any links yet, just refresh the page.

So I made something similar to ays-beforeunload-shim.js like this:

var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );
if(iOS){

window.onunload = function() {              
 var response = $(window).triggerHandler('beforeunload', response);
if (response && response != "") {
    var msg = response + "\n\n"
      + "Press OK to leave this page or Cancel to stay!!!.";
    if (!confirm(msg)) {
      return false;
    }
  }
}

}

I can see the message but cannot prevent reloading page even I clicked "Cancel" on the prompt.

Is there anyway to make this done?

Type error on line 52 in 1.7

Hello!
Thanks for adding support for elements without name attribute.
If try to initialize AYS on select without option elements it will be TypeError (Firefox 29) on line 52, because val() returns null.
I can't send pull request now, but it's easy to fix that.
Replace

val = $field.val().toString();

to

var tval = $field.val();
val = tval != null ? tval.toString() : null;

Best regards.

Not work if name attribute not set

Hi. I develop ajax form and faced with one little trouble. if input don't have name attribute it don't checks by AYS. May be this fact should be reflected in the documentation or anything else.

Click on the anchor tag will popup the message in IE

If you have anchor tag with href="jquery:void(0)" in the form and click on the anchor tag
it will generate beforeunload event. I hope we can have some kind of workaround so that it doesn't do that on IE9/10

property 'settings' of undefined

Hi Team,

I have form inside another form and the AreYouSure is registered on the main form. I am getting the below issue when I click on input control to Edit. I have used AreYouSure on nested forms but never faced any issue. But in this form, when I click on any input control, I am getting this error.

StackTrace: TypeError: Cannot read property 'settings' of undefined
at e (http://localhost:8889/Scripts/jquery.validate.min.js:2:4816)
at HTMLFormElement. (http://localhost:8889/Scripts/jquery.validate.min.js:2:20926)
at HTMLFormElement.x.event.dispatch (http://code.jquery.com/jquery-2.0.3.min.js:5:10006)
at HTMLFormElement.y.handle (http://code.jquery.com/jquery-2.0.3.min.js:5:6796)
at Object.x.event.trigger (http://code.jquery.com/jquery-2.0.3.min.js:5:9131)
at Object.x.event.simulate (http://code.jquery.com/jquery-2.0.3.min.js:5:12406)
at HTMLDocument.r (http://code.jquery.com/jquery-2.0.3.min.js:5:13723)

ASP Net Hidden fields and Telerik drama

I know who uses this crap still... apprantly big public companies.

Problem spotted when I want to vcalidata all pages and a simple page with postback selector caused issues because of Telerik radcontorllor hidden input chaning and failing the brute force checker.

My Fix

 var getValue = function ($field) {
            debugger;
            if ($field.hasClass('ays-ignore')
                || $field.hasClass('aysIgnore')
                || $field.attr('data-ays-ignore')
                || $field.closest('.aspNetHidden')  // <-----------------------
                || $field.attr('name') === undefined) {
                return null;
            }

Just ignore all asp hidden values and viewstates and all that or possible allow to pass in extra classes in the options to ignore on.

image

The moment where you test the field, and this hidden one tests true even though the user did not touch this. Maybe Hiddens should be completely ignore??

image

Doesn't work on Opera, no custom message on Firefox

I just tested the demo page on Opera 12.14. The plugin did present the confirmation on page changes.

I also tested the demo page on Firefox 18. It worked, but the message could not be customized. The custom message appears on IE 9 and Chrome.

trigger dirty()

Hi codedance,

First off ๐Ÿ‘ to this! My question, is there a way or how do I trigger something like a $('form_tagged_as_areyousure').is_now_dirty() ? Like, to programmatically tag a form as dirty?

I have a form with a draggable div that I want when that changes I would mark the form as dirty already and when they close, it counts as dirty already and confirmation would popup.

Cheers!

Can you modify to detect changes within table cells?

It would be very handy to have it detect changes within tables on the form. I understand that storage of original values in large tables might be problematic, but at least from my perspective I can live with that not happening.

Able to Bypass Prompt if Link Clicks Are Close Together

Hey there!

I want to first say thanks for the plugin!

I started using this plugin at v1.6 and did not have any issues.

I just recently upgraded to v1.7 for the safari support but I noticed an issue in v1.7 that I cannot duplicate in v1.6.

With v1.7, if I make my form dirty and then repeatedly click a link on the page and answer 'stay on the page', I am eventually navigated away from the page without receiving the confirmation popup. This occurs if my link clicks and answers to the prompt to stay on the page are quick, approximately a second or two apart from each other.

To illustrate my point, consider the following sequence of events (note this is just an example, not the only sequence that results in the issue):

  1. make form dirty
  2. click link 1 @t=0
  3. answer prompt with 'stay on the page' @t ~= 1 sec
  4. click link 1 @t ~= 1 sec
  5. answer prompt with 'stay on the page' @t ~= 2 sec
  6. click link 1 @t ~= 2 sec
  7. no prompt received, navigated to link 1 target

The problem is not browser-specific; I was able to produce this issue using v1.7 in chrome, firefox, and IE.

Brian

ASP --doPostBack

Sorry to inundate you with issues from legacy systems, but as you can see they are still in use.

The problem off course is the daft way ASP triggers post backs, from "a" links or other types. Obviously that is out of HTML specification now a days... but bad smells can linger around for a long time :( So when I click save it shows nag screen instead of saving as expected.

image

Fires this garbage... (which I don't know how to amend and don't want to waste my life trying to find out too, since it gets injected by ASP somewhere.)

image

and sadly NEVER reaches this code :(

image

I intiliase the plugin with this, on form, ASP only ever has 1 form, which you cant rely on the id being the same, ever.

<script type="text/javascript">
        $(document).ready(function () {
            $('form').areYouSure({ 'message': 'You have un-saved changes.' });
        });
</script>

I will try to find a fix and publish it here, just in case it seems viable to push upstream.

Thanks

Dirty change event support

The aim is to keep Are-you-sure simple and light. One possible feature extension though is to add event support so you can intercept the dirty state change in your own code. If you think this is a good idea, please comment on this issue.

Not working for imagebutton event

Hi,
The dirty check is not happening when click in the imagebutton.I had image button to go next and previous date of date picker.I had added the dirty check method as below:
<asp:ImageButton ID="lnkNextPeriod" ImageUrl="/images/pointer-right.png" CssClass="lnkNext"
OnClientClick="$('form').trigger('checkform.areYouSure');" OnClick="lnkNextPeriod_Click" runat="server" />

Thanks
Sabin

dirty state lost after failed validation

Let's say I changed an input, the dialog shows up just fine if I try to leave the page. But if I click the save button and there's a falied validation (client o server side) then I try to leave the page the dialog does not show and let me leave the page. It's as it beleive that the form is clean again.

Checking which button was clicked...

Is there a way to test the the result of the AYS result in a function that is fired later? I want to test the value in an onclick function, and do different things based on what the user clicked. Any ideas?

default field selector

I had an issue when I set addRemoveFieldsMarksDirty to true in IE 11. I had button tag on the for and this was being included in the ays-orig-field-count which caused the warning to be shown/not shown inappropriately. Changing the default fieldSelector to ":input:not(input[type=submit]):not(input[type=button]):not(button)" resolved the issue.

Checking for the 'name' attribute again

Example.
I have a form with hidden field. I use this field for checking complex structure for changes (serialize and write when this structure changes). After writing to field I trigger checkform.areYouSure.
As you can see this field without name attribute.

<input type="hidden" id="fiasAddressBoxHash" />

So, AYS does not get value of this field, because function getValue checks for name attribute:

$field.attr('name') === undefined

and return null if it undefined. When I delete this checking it works as expected.
In 1.8 and 1.9 branch this checking exists too.

UPD: something works wrong without this checking.
UPD2: Facepalm.jpg. It kendoNumericBox input without name and id. It I can fix in my form by setting 'fieldSelector' option, I hope.

Constant nagging in chromium as implemented in Zenphoto

Using Chromium, I get nagged that there are unsaved changes even when all I do is click from one tab to the another in Zenphoto's admin interface (the tabs in the page, not the browser tabs) without interacting with any form or drop-down or other button.

Disabled adblock-plus and referer-control extensions, no difference.

Tested in chromium-35.0.1916.114-r1 and chromium-36.0.1985.49 using the version shipped with Zenphoto 1.4.6 as well as the latest version here from github which is from May 28.

Same issue opened in the Zenphoto forum: http://www.zenphoto.org/support/topic.php?id=1074500

Clicking a form's reset button still leaves the form dirty

If you have a reset button on a form and that is pressed the form status doesn't change from dirty to no changes so you can't navigate away. This is true on the latest firefox and chrome.

You can bind to the form reset event but the form values haven't changed at that point so I just have to manually mark the form as clean.

Here's a quick patch to fix it but it's not a very nice solution:

// Line below is existing code, insert the rest below it
$(this).find(settings.fieldSelector).bind('change keyup', checkForm);

$(this).bind('reset', function() {
  $(this).toggleClass(settings.dirtyClass, false);

  // Fire change event if required
  if (settings.change) {
    settings.change.call($(this), $(this));
  }
});

Dirty call on post back in asp.net

Hi all,

we are using plugin in asp.net, in that we are doing text box auto post back get data from the database, so at that time its how the prompt message

how to avoid it?

ASPX code
<asp:TextBox ID="txtLoginId" runat="server" MaxLength="10" SkinID="TextLarge" data-ays-ignore="true" class="ays-ignore"
OnTextChanged="txtLoginId_TextChanged" AutoPostBack="true" >/asp:TextBox

//Calling method

$(document).ready(function () {
$('#form1').areYouSure();

    });

Thanks in advances please let me kn ow its very urgent

Readme update request

Simple request to add the list of "modern browsers" that are supported. Thanks for a great easy to use plugin!

CKeditor support

Hi,

You can add CKeditor support. Just simply add following code into your solution.

checkForm()

(...)
// ckeditor
if (typeof (evt.editor) !== 'undefined') {
if (CKEDITOR.instances[evt.editor.name].checkDirty()) {
setDirtyStatus($("#" + evt.editor.name).parents('form'), true);
return;
}
}

(...)

initForm()

(...)
//ckeditor
if (typeof(CKEDITOR) !== 'undefined') {
CKEDITOR.on('instanceReady', function () {
for (var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].removeListener("change", checkForm);
CKEDITOR.instances[instanceName].on("change", checkForm);
CKEDITOR.instances[instanceName].removeListener("keyup", checkForm);
CKEDITOR.instances[instanceName].document.on("keyup", checkForm);
}
});
}
(...)

selects with optgroups not tracked

When a select contains optgroups, the selected value is not tracked correctly, and changes in the value will not mark the form as dirty.

For example, select such as follows will not have the field's original selected value nor the changed value correctly checked.

<select>
 <option></option>
 <optgroup label="Fruit">
   <option value="banana">Banana</option>
   <option value="pineapple" selected="selected">Pineapple</option>
 </optgroup>
 <optgroup label="Vegetable">
    <option value="carrot">Carrot</option>
 </optgroup>
</select>

This seems to be because the getValue function retrieves the current value of a select with jQuery.children() on the select element, which only selects immediate children:

        case 'select':
          val = '';
         $field.children('option').each(function(o) {
            var $option = $(this);
            if ($option.is(':selected')) {
              val += $option.val();
            }
          });
          break;

This means the val is left empty, both on initial check for the original value, as well as the check for the changed value.

Changing the getValue code to use jQuery.find() does seem to make it correctly handle also selects with optgoups.

jqte rich text plugin support

Hi,

Are you sure is not supporting with rich text area jqte plugin, though jqte changes the textarea value dynamically.

Does not work with Ipad/Iphone

Has anyone figured out how to make this work with Ipad/Iphone browsers?

They do not handle the 'beforeunload' event properly and I've been beating my head trying to figure out how to issue a message if anything in the form changes. I tried your module and used 'pagehide' instead of 'beforeunload', but it did not work.

Developer friendly suggestion

While attaching to $.fn there is a check that element is actually a form which silently returns if not working with a form.

  return this.each(function(elem) {
      if (!$(this).is('form')) {
        return;
      }

It might be user friendly to add some kind of notification if the test is true. For example, this use of console before returning.

    return this.each(function(elem) {
      if (!$(this).is('form')) {
        if (console && console.log) {
           console.error("jquery.AreYouSure can only attach to <form> elements");
        }        
        return;
      }

This might help out people who use a selector that's too broad or contains a typo. (Been there...)

Throwing an exception is another possible solution, i.e.

      if (!$(this).is('form')) {
           throw new Error("jquery.AreYouSure can only attach to <form> elements");
      }

A bit more drastic and possibly unwarranted in some circumstances. Highly effective though without adding a lot of weight.

input[type=hidden] is not being checked for dirty

The input[type=hidden] is not getting checked for dirty because neither the change or keyup events are getting fired on change of the value.

Work around that i am using is to trigger the keyup event when the change is done to the input[type=hidden] value.

Thank you for this great and easy plugin!

input tag with no name causing issues ?

It seems that an input tag with no name stop AreYouSure to ignore fields with data-ays-ignore="true" from the dirtyness check.
I didn't look for other issues.
Anyway, after this little addition to your class :

if ($field.hasClass('ays-ignore')
    || $field.hasClass('aysIgnore')
    || $field.attr('data-ays-ignore')
    || $field.attr('name') === undefined /* addition */ ) {
    return null;
}

everything works fine.

rescan()

rescan() needs work

  • You are checking for attribute [ays-orig], which is never set anywhere. I guess you only want to pick up fields not existing before.
  • Subsequently all matchings fields are rescaned (no problem with this as I want to refresh the values after I have saved the form via ajax), but bind handlers are rebound each time and duplicated.

For my purposes the rescan should be complete, or support a 'all' parameter.
Perhaps use namespaces for the events as well.
I'm no JS expert, so feel free to question or criticise anything I said :)

var rescan = function(all) {
  var $form = $(this);
  var fields = $form.find(settings.fieldSelector);
  if (!all) fields = fields.not("[ays-orig]");
  $(fields).each(storeOrigValue);
  $(fields).unbind('change.areYouSure keyup.areYouSure', checkForm).bind('change.areYouSure keyup.areYouSure', checkForm)
};

Does not work for hidden

Hello, ays does not work with input[type="hidden"], because browsers does not trigger "change" event for hidden inputs.
I trigger change for all hidden items in the forms
This changes works for me:

 $(window).bind('beforeunload', function () {
            //!!!hack 
            var hiddenFields = $("form").find(settings.hiddens);
            $(hiddenFields).each(function () { $(this).trigger("change"); });
            //end hack
        $dirtyForms = $("form").filter('.' + settings.dirtyClass);
        if ($dirtyForms.length > 0) {
          // $dirtyForms.removeClass(settings.dirtyClass); // Prevent multiple calls?
          return settings.message;
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.