开发者

Change text input's value if invalid

Hi Im using jQuery's validate (awesome) script to validate a small form. It is just an email sign up and there isn't a lot of room around it to display the error message. I can change the input's value to "Thank You" with successful AJAX submission, but want to change it to display the correct error msg if its invalid.

HTML

<div id="emailBox">
    <form id="email" action="/PHP/email-cURL.php" method="post">
    <input type="text" id="e" name="email1" value="Email Sign Up" class="swap_value signup" />
    <input type="submit" value="" id="signUp" />
    </form>
</div>

and the JS

$("#email").validate ({
        errorElement: "//what do I wrap error msg in to populate value?",
            errorPlacement: function(error, element) {
                error.appendTo( element.parent("div"));
            },

            submitHandler: function(form) {
            var dataString = $(form).serialize();
                $.ajax({
                    type: $(form).attr('method'),
                    url: form.action,
                    data: dataString,
                    clearForm: true,
                    success: function(data) {
                        if (data=="Error") {
                            $("#e").val('Error');
                        } else {
                            $("#e").val('Thank You');
                            }
                    }
                });
            return false;

           },
                       //rules,
                       //mes开发者_Go百科sages 

Is there an easy way to do this? I don't need a ton of code since its just one simple form input.

Thanks!


Try returning JSON. This PHP code:

echo json_encode(array('success'=>false,'errorMsg'=>'Failed to set x');

outputs this JSON:

{"success":false,"errorMsg":"Failed to set x"}

And adjust your code to handle the JSON

    var dataString = $(form).serialize();
            $.ajax({
                type: $(form).attr('method'),
                url: form.action,
                data: json,
                clearForm: true,
                success: function(data) {
                    if (undefined !== data && true === data.success) {
                        $("#e").val('Thank you');  
                    } else {
                        var error = undefined === data.errorMsg ? 'Unknown error' : data.errorMsg;
                        $("#e").val(error);                                                        }
                }


Send JSON back to the client, something like:

{ "status" : "error", "message" : "Email address already exists" }

and on the client, set $.ajax's dataType option to 'json', and access the properties of the returned object:

success: function(json) {
             if (json.status == "error") {
                 $("#e").val(json.message);
             } else {
                 $("#e").val('Thank You');
             }
         }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜