jQuery 自动完成 - 阻止提交任何不是自动完成数组中的值的内容

jQuery Autocomplete - Prevent submit of anything that is not a value from the autocomplete array?

本文关键字:数组 提交 jQuery 任何不      更新时间:2023-09-26

我正在尝试使用jQuery自动完成搜索表单在网站上创建"跳转到页面"类型的搜索。

在此表单上,我有两个文本输入字段。一个是用户看到的(#tags(,另一个是隐藏的(#propertylink - 我在 JSFiddle 中使其可见,以便更容易理解我的代码中发生了什么。此值用于将 get 变量发送到下一页,然后用于生成下一页上的内容。

我已经设置了表单,以便当用户单击自动完成建议(来自我的 JS"源"数组的"标签"(时,单击的相应源的"值"的值随后被输入到隐藏的 #propertylink 字段中,并且源的"标签"值同时输入到可见 #tags 输入字段中。

当隐藏的 #propertylink 字段变得可见时,我将提交按钮设置为淡入,切换到启用,然后单击提交按钮将使用 #propertylink GET变量将用户带到生成的页面。在这种情况下一切都很好,但是,问题是,如果用户不选择自动完成建议之一。

如果用户改为单击提交按钮而不单击自动完成选项,则不会为 #propertylink 字段分配 get 变量值。如何使只有我的 JS 变量"源"数组值触发提交按钮出现?现在,它只是在输入字段不为空时显示。

我是JS和Jquery的新手,我只需要一点帮助才能使最后一部分正常工作。

<div class="ui-widget">
<form method="get" action="listing-detail.php">
  <input id="tags" type="text"/>
  <input id="propertylink" type="hidden" name="list_id"/>
  <input class="sendButton" type="submit" value="Go">
  </form>
</div>

<script>
$(document).ready(function() {
var source = [
            { 
              value: "910091432",
              label: "123 Fairfax Ln"
            },
            { 
              value: "910091433",
              label: "567 The Shire Ln"
            }
             ];
    $("input#tags").autocomplete({
        source: function(request, response) {
        var results = $.ui.autocomplete.filter(source, request.term);
        response(results.slice(0, 35)); /* this is just to limit the amount of results to 35 */
    },
        focus: function( event, ui ) {
        $( "#tags" ).val( ui.item.label );
        return false;
      },
        select: function( event, ui ) { 
        $( "input#propertylink" ).val( ui.item.value ),
        $( "#tags" ).val( ui.item.label );
        return false;
        }
    });
});
$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#tags').keyup(function(){
        if($(this).val().length !=0)
            $('.sendButton').attr('disabled', false).fadeIn(500);            
        else
            $('.sendButton').attr('disabled',true).fadeOut(500);
    })
});
</script>

https://jsfiddle.net/3d13daxj/1/

编辑:有关最终修复,请参阅下面的编辑。

我在你给出的 jsfiddle 链接中对此进行了测试。我以前从未使用过 jsfiddle,但这似乎工作得很好。

您的最后一个函数目前如下所示:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#tags').keyup(function(){
      if($(this).val().length !=0)
        $('.sendButton').attr('disabled', false).fadeIn(500);            
      else
        $('.sendButton').attr('disabled',true).fadeOut(500);
   })
});

我在"onkeyup"函数内的 if 语句中添加了以下内容:

$('#tags').keyup(function(){
  if($(this).val().length !=0)
    if($("#tags").val()=="123 Fairfax Ln")
      $('.sendButton').attr('disabled', false).fadeIn(500);                                                       
    else
      $('.sendButton').attr('disabled',true).fadeOut(500);
    else
      $('.sendButton').attr('disabled',true).fadeOut(500);
    })

不过,这只是为了测试它,它奏效了。如果输入字段与"123 Fairfax Ln"不匹配,则"Go"按钮将消失,或者根本不显示。

您可以通过创建一个填充所有可接受值的数组来替换我的测试,然后将我添加的 if 语句放在 for 循环中。

它将看起来像这样:

var arrayOfAcceptableValues = ["Fill with all acceptable values"];
$('#tags').keyup(function(){
  if($(this).val().length !=0)
    for(i=0; i< arrayOfAcceptableValues.length;i++)
    // This will loop through all the values in your array.
      var testCase = arrayOfAcceptableValues[i];
      if($("#tags").val()== testCase)
      // This is the test to see if the value entered by the user is actually one of your predetermined acceptable values.
        $('.sendButton').attr('disabled', false).fadeIn(500);                                                         
      else
        $('.sendButton').attr('disabled',true).fadeOut(500);
    else
      $('.sendButton').attr('disabled',true).fadeOut(500);
    })

只是最后一句忠告。我建议您配置第二个输入,以便当第一个输入为空时,它也为空。在我清除第一个输入的那一刻,自动填充在那里的生成值不会消失。作为安全预防措施,我会在第一个输入为空时自动清除该输入。

希望对您有所帮助!

编辑:修复了点击问题和其他一两个问题。

所以我在几个地方更改了你的代码,但我会解释我做了什么以及这些更改修复了什么。

新的 java 脚本代码如下所示:

$(document).ready(function() {
  var source = [
            { 
              value: "910091432",
              label: "123 Fairfax Ln"
            },
            { 
              value: "910091433",
              label: "567 The Shire Ln"
            }
             ];
    // I moved this line here so that the button functions properly.
    $('.sendButton').attr('disabled',true);
    $("input#tags").autocomplete({
        source: function(request, response) {
        var results = $.ui.autocomplete.filter(source, request.term);
        response(results.slice(0, 35));
    },
        focus: function( event, ui ) {
        $( "#tags" ).val( ui.item.label );
        return false;
      },
        select:function(event, ui){
          $( "input#propertylink" ).val( ui.item.value ),
          $( "#tags" ).val( ui.item.label );
          return false;
        }
    });
  // -Event Listeners:
  $("#tags").on( "change", function(){}).change();
  $("#tags").on("autocompleteselect", goButtonVisibility);
  $("#tags").keyup("autocomplete",goButtonVisibility);

});

函数goButtonVisibility(e,ui( { if($("#tags"(.val((.length !=0( { if($("#tags"(.val((=="123 Fairfax Ln"( { $('.sendButton'(.attr('disabled', false(.fadeIn(500(;
} 还 { $('.sendButton'(.attr('disabled',true(.fadeOut(500(; } } 还 { $('.sendButton'(.attr('disabled',true(.fadeOut(500(; } }

你会看到我删除了第二个"$(document(.ready..."您在自动完成下方拥有的功能。我获取了"keyup"函数中的代码,并将其放在一个新函数"goButtonVisibility"中。我认为代码与以前完全相同。

您还会注意到以下三行:

$("#tags").on( "change", function(){}).change();
$("#tags").on("autocompleteselect", goButtonVisibility);
$("#tags").keyup("autocomplete",goButtonVisibility);

第一个将操作侦听器放在 #tags 字段上,并侦听任何更改。当用户单击链接而不是使用键盘时,将触发中间代码行。然后,这将解决此问题。最后一行几乎是您的"键控"功能。

此问题已修复:

  • 您的原始问题。
  • 点击问题。
  • 它修复了一个错误,用户可以选择一个选项,该选项启用"Go"按钮,但用户可以返回编辑选择,而无需再次禁用"Go"按钮。
  • 它还修复了一个错误,用户可以键入例如"a"并将鼠标悬停在下拉项上。该字段将填充将悬停在上面的项目,并且"开始"按钮将启用。但是,用户可以将光标从下拉菜单中移开,该字段返回到仅显示其搜索词(在示例中为"a"(,但"Go"按钮将保持启用状态。

如果还有其他事情,错误或您希望我解释的内容,请告诉我!