如何强制停止用户在jquery ui自动完成中提交页面数据?

时间:2012-09-14 07:19:54

标签: asp.net-mvc-3 jquery-ui jquery-ui-autocomplete

我在使用mvc3开发的网站中使用了jquery ui。 I used jquery ui auto-complete mechanism.

我使用了以下jquery函数 -

/// script to load owner for owner dropdown.
$(function () {
    $("#Owner_FullName").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Employee/AutocompleteSuggestions",
                type: "POST",
                dataType: "json",
                data:
                    {
                        term: request.term
                    },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.FullName, value: item.Id }
                    }
                    ))
                }
            })
        },
        minLength: 1,
        focus: function (event, ui) {
            $("#Owner_FullName").val(ui.item.label);
            return false;
        },
        select: function (event, ui) {
            if (ui.item) {
                $("#Owner_FullName").css('border', '');
                $("#Owner_FullName").val(ui.item.label);
                $("#OwnerId").val(ui.item.value);
                return false;
            }
        },
        change: function (event, ui) {
            if (ui.item == null) {
                $("#Owner_FullName").css({ 'border': '1px solid #ff0000' });
                $("#OwnerId").val(null);
            }
        }
    });
});

我在文本框中显示了所有者名称,并将OwnerId设置为隐藏字段以供进一步处理。

对于处理用户在文本框中键入而不是从下拉列表中选择项目的情况,我使用了更改事件,并且在该事件上我使用reset hiddden字段为null并将css应用于文本框。

现在我的问题是我的文本框字段不是必填字段,如果用户在文本框中键入并只是提交数据,那么它应该显示警告类型的消息,并且在文本框值被清除之前不应发生提交过程用户

如何处理?

1 个答案:

答案 0 :(得分:0)

如果要在用户只是在自动填充框中键入值而不从下拉列表中选择时显示错误条件,则可以使用自动填充的change事件突出显示此更新隐藏字段。< / p>

change: function (event, ui) {
  if (ui.item == null || ui.item == undefined) {//I also use the undefined check
    $("#OwnerId").val("");//I have never used null before when using val(). But you always want to clear out the hidden field if the user does not select from the drop down.
      if ($.trim($("#Owner_FullName").val()) == "") {//check and see if the user cleared the field out
        $("#Owner_FullName").css({ 'border': '' });
        //The autocomplete field is blank. Then put code here that allows the submit.
        }
          else
       {
          $("#Owner_FullName").css({ 'border': '1px solid #ff0000' });
          //The autocomplete field is NOT blank. Then put code here that prevents the submit.
       }//close the if = "" statement
    }
  }//close function

另一个选项可能是检查提交时的自动填充字段以查看是否选择了某些内容,如果选择了 NOT ,则停止发布。您可以检查自动填充是否从列表中选择了......

$("#Owner_FullName").data("autocomplete").selectedItem != null //or undefined for that matter

如果其中任何一个适合您,请告诉我们!