0

I am having trouble with jquery notification formReset() with "e.preventDefault();" and gritter notifications. In my code, I am calling the eventAdd() function to the submitHandler of validator. In the eventAdd function, I am calling a gritter notification. Everything works fine except the form reset part, if I remove the e.preventDefault(). When I remove it, form doesn't get a reset and everything shows up green after submit. Here is the code for formReset and eventAdd functions (They're both wrapped in $(document).ready function and non related parts of the code are deleted for simplicity).

var form1 = $('#form1');
var error1 = $('.alert-error', form1);
var success1 = $('.alert-success', form1);

var validator = form1.validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-inline', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    ignore: "",
    rules: {
        title: {
            minlength: 2,
            required: true
        },
        description: {
            minlength: 2,
            required: true
        },
        Date: {
            required: true,
            trDate: true
        },
        time_Begin: {
            required: true,
            trHour: true,
        },
        time_End: {
            required: true,
            trHour: true,
        }
    },

    errorPlacement: function (error, element) {
        if (element.next().is('.add-on')) {
            error.addClass('class1').insertAfter(element.next('.add-on'));
        } else {
            error.insertAfter(element);
        }
    },

    invalidHandler: function (event, validator) { //display error alert on form submit              
        success1.hide();
        error1.show();
        App.scrollTo(error1, -200);
    },

    highlight: function (element) { // hightlight error inputs
        $(element)
            .closest('.help-inline').removeClass('ok'); // display OK icon
        $(element)
            .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
    },

    unhighlight: function (element) { // revert the change done by hightlight
        $(element).closest('.control-group').removeClass('error'); // set error class to the control group
    },

    success: function (label) {
        label.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
    },

    submitHandler: function (form) {
        eventAdd();
    }
});

function eventAdd() {
    $.gritter.add({
         title: 'SUCCESS!',
         text: 'Event saved successfully.',
         sticky: false,
         time: '10000'
    })

    e.preventDefault();   // That is preventing the gritter notification
    validator.resetForm();
}

I cannot think of anything to keep both the gritter and successfull resetForm functions working. Any ideas?

EDIT: HTML code

<form id="form1">
    <div class="alert alert-error hide">
        <button class="close" data-dismiss="alert"></button>
        Please fix the error fields.
    </div>
    <div class="alert alert-success hide">
        <button class="close" data-dismiss="alert"></button>
        All fields are OK. You can save your event.
    </div>

    <div class="control-group">
        <div class="controls">
            <input id="event_title" name="title" data-required="1" type="text" value="" class="m-wrap span11 tooltips" placeholder="Event Title..." data-trigger="hover" data-original-title="Write your event description." data-placement="bottom" />

        </div>
    </div>

    <div class="control-group">
        <div class="controls">
            <textarea id="event_description" name="description" data-required="1" class="m-wrap span11 tooltips" placeholder="Event Description..." rows="5" style="resize: vertical;" data-trigger="hover" data-original-title="Etkinlik açıklamanızı yazarken HTML etiketleri kullanabilirsiniz. Açıklamanızı en fazla 1000 karakter (HTML etiketleri dahil) olarak girin." data-placement="bottom"></textarea>

        </div>
    </div>

    <div class="control-group">
        <div class="controls">
            <div class="input-append" id="ui_date_picker_trigger">
                <input id="ui_date_picker_change_date" name="Date" data-required="1" placeholder="Event Date" class="m-wrap span6" type="text" value="" />
                <span class="add-on"><i class="icon-calendar"></i></span>
            </div>
        </div>
    </div>

    <div class="control-group">
        <div class="controls">
            <div class="input-append" id="ui_time_picker_trigger_Begin">
                <input id="ui_date_picker_change_time_Begin" name="time_Begin" placeholder="Event Begins" class="m-wrap span6" type="text" value="" /><span class="add-on"><i class="icon-time"></i></span>
            </div>
        </div>
    </div>

    <div class="control-group">
        <div class="controls">
            <div class="input-append" id="ui_time_picker_trigger_End">
                <input id="ui_date_picker_change_time_End" name="time_End" placeholder="Event Ends" class="m-wrap span6" type="text" value="" data-placement="top" /><span class="add-on"><i class="icon-time"></i></span>
            </div>
        </div>
    </div>

    <hr />
    <button id="event_add" type="submit" class="btn blue tooltips" style="float: left;"><i class="icon-ok"></i>&nbsp;Add Event</button>
    <button id="event_nullify" type="submit" class="btn yellow tooltips" style="float: right;"><i class="icon-refresh"></i>&nbsp;Cancel</button>
</form>
ilter
  • 4,030
  • 3
  • 34
  • 51
  • That's not what `preventDefault()` is meant for. It's for preventing the default behavior of certain events, like stopping the history when you click an anchor link. And it does nothing when you neglect to pass the `event` (`e`) argument into the function. See the documentation: http://api.jquery.com/event.preventDefault/ – Sparky Oct 07 '13 at 17:17
  • Also show a more complete demo of your code. (where is your HTML markup?) – Sparky Oct 07 '13 at 17:20
  • When I remove the e.preventDefault(), form doesn't get a reset on submit. When it is there, it works. I will try to simplify the code a little bit and update the question. Just a min. – ilter Oct 07 '13 at 17:22
  • Actually, the e.preventDefault() function here is preventing the page from reloading after submit. When I remove it page submits and reloads. That is why I thought the form is getting the reset :( Actually, it was getting it's pageload state after the postback. I guess my problem is with the resetForm function, then... – ilter Oct 07 '13 at 17:29
  • Bottom line is that you're not using `preventDefault()` properly and your page is broken. I cannot see enough code to explain your observations but on a regular submit the page reloads by default and a JavaScript error can also prevent that, thanks to the `submitHandler` of the plugin. – Sparky Oct 07 '13 at 17:31
  • In other words, putting broken code into the plugin's `submitHandler` callback function can have the same effect as putting a `return false` in there... the regular submit is blocked. – Sparky Oct 07 '13 at 17:37

1 Answers1

1

1) Your usage of e.preventDefault() is incorrect and unnecessary. If you simply want to block the regular form submit, then put a return false at the end of the submitHandler callback function.

    submitHandler: function (form) {
        eventAdd();
        return false; // block form submit
    }

2) You are missing a comma right after your rules option.

    rules: {
        title: {
            minlength: 2,
            required: true
        },
        description: {
            minlength: 2,
            required: true
        }
    }, // <-- this comma was missing

3) The plugin's resetForm() method is for resetting the validation only... removing any error messages and returning the form to its initial validation state. It will not, however, remove any data entries from the fields.

Edit: Since you're only calling it from submitHandler, it will never do anything. That's because submitHandler only fires on a valid form.

Add a line with $('form').get(0).reset() if you want to clear out the fields.

function eventAdd() {
    $.gritter.add({
       title: 'SUCCESS!',
       text: 'Event saved successfully.',
       sticky: false,
       time: '10000'
    });
    // validator.resetForm();     // reset validation - superfluous here
    $('form').get(0).reset();     // clear the fields
}

Working DEMO: http://jsfiddle.net/t3dtG/

Edit: .resetForm() is only for resetting the validation (removing outstanding error messages). I removed .resetForm() above because it's superfluous in this context. The submitHandler only fires when the form is valid, therefore, there is nothing for resetForm() to do.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • $('form').get(0).reset(); is how I solved the form entry reset. But validator.resetForm(); does nothing in my case. I solved the error and success colorings by removing the classes from the control-group divs by $('.control-group').removeClass('error').removeClass('success'); code. Thanks for the help, though! You pointed me to the right direction :) Why do you think validator.resetForm(); didn't work out? – ilter Oct 07 '13 at 19:45
  • @ilter, as explained in my answer, it's the reset method of the validator... it only removes outstanding validation messages and resets the form validation... it's working fine but you _think_ it's not working because you have no errors on the form. In other words, it's never going to do anything in your case since the `submitHandler` only fires when the form is valid. – Sparky Oct 07 '13 at 19:49