1

I'm trying to Validate my form before it's being sent to the server. I tried couple of J/S plugins for regular validation and none of them seem to work.

I tried looking for getJSON validation method with jquerymobile but haven't seen anything related. Is using $.getJSON the right approach?

Here is a fiddle http://jsfiddle.net/Kimbley/kMsXK/2/

Thanks :D

Code Here:

    function mAddBusiness() {
        $.getJSON("API.php", {
            command: "addBusiness",
            bsnName: $("#mBsnName").attr("value"),
            bsnCity: $("#mBsnCity").attr("value"),
            bsnAddress: $("#mBsnAddress").attr("value"),
            bsnMenu: $("#mBsnMenu").attr("value"),
            bsnLat: bsnLat,
            bsnLong: bsnLong
        },
            function () {
            $("#mBsnName").attr("value", "");
            $("#mBsnCity").attr("value", "");
            $("#mBsnAddress").attr("value", "");
            $("#mBsnMenu").attr("value", "");
            alert("Business was added successfully ");
        }
            );
    }
4

1 回答 1

0

在您的mAddBusiness()函数中,您可以在发送 AJAX 请求之前进行验证。就像是:

function mAddBusiness() {
    if ($("#mBsnName").val() !== '') {
        $.getJSON("API.php", {
            command: "addBusiness",
            bsnName: $("#mBsnName").val(),
            bsnCity: $("#mBsnCity").val(),
            bsnAddress: $("#mBsnAddress").val(),
            bsnMenu: $("#mBsnMenu").val(),
            bsnLat: bsnLat,
            bsnLong: bsnLong
            },
            function () {
                $("#mBsnName").val("");
                $("#mBsnCity").val("");
                $("#mBsnAddress").val("");
                $("#mBsnMenu").val("");
                alert("Business was added successfully ");
            }
        );
    } else {
        alert('Please enter a business name.');
    }
}

请注意,您必须将data-ajax="false"属性添加到相关<form>标记中,以便 jQuery Mobile 不会尝试提交表单本身。

另外,请注意$('input').attr('value'),它不会返回输入的当前值,它会在用户有机会输入任何内容之前返回初始值。要获取表单输入的当前值,请使用.val()http ://api.jquery.com/val

于 2012-07-10T20:25:46.307 回答