Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate plugin with alert popup - still appears - the user can't choose correct value in select box

I'm using following code:

$().ready(function() {
    $('#state_form').validate({
        rules: {
            state: "required"
        },
        messages: {
            state: 
            {
                required: "The State is required!"
            }
        },          
        errorPlacement: function(error, element) {
            alert(error.html());
        }
    });
});

but if the user submits the form then popup with error appears. This is correct. Then if the user clicks to the selectbox 'state' the popup with error still appears (is not possible choose correct value). The real example is available at janzitniak.info/temp/test.php

This is not acceptable. How could I resolve this problem?

The solution described at JQuery form validation with alert popup - alert still being shown with a valid submit didn't help me, maybe I didn't understand that correctly.

like image 1000
JanZitniak Avatar asked Feb 10 '13 18:02

JanZitniak


1 Answers

Use the onclick: false option to prevent the error from triggering before the state is selected. Also, you only need to use .text() instead of .html() because the alert() will not need to use the HTML anyway.

$(document).ready(function () {
    $('#state_form').validate({
        onclick: false, // <-- add this option
        rules: {
            state: "required"
        },
        messages: {
            state: {
                required: "The State is required!"
            }
        },
        errorPlacement: function (error, element) {
            alert(error.text());
        }
    });
});

Demo: http://jsfiddle.net/U6N3R/

CAUTION: Do not use this code in Safari or you will be stuck in an infinite loop. It seems like the alert() in Safari fires the errorPlacement callback function a second time after clicking "ok" button.


For a more modern user experience, I recommend a jQuery modal or tooltip plugin instead.

See this answer as an example: https://stackoverflow.com/a/14741689/594235

like image 97
Sparky Avatar answered Nov 15 '22 10:11

Sparky