根据文本字段中的用户输入隐藏/显示复选框

Hide/show checkboxes based on user input in text field

本文关键字:隐藏 输入 显示 复选框 用户 文本 字段      更新时间:2023-09-26

您可以在此处查看我当前的html/css/jshttps://jsfiddle.net/cu0cvem2/.当我有实际内容时,"组"(复选框列表)会长很多。我需要用户能够开始在输入字段中键入内容,并缩小可用的复选框。例如,如果他们开始键入"grou",那么所有复选框都将仍然存在,因为它们都包含"group"。如果开始键入"酷",他们将只剩下一个复选框"酷组"可供选择。

我希望能够将此代码添加到我用来隐藏和显示复选框的当前对象中,复选框如下所示:

StoryGroup = {
  groupInput: '.story-group-container input[type="text"]',
  container: '.checkbox-container',
  submit: '.checkbox-container .filter',
  body: 'body',
  init: function() {
    $(this.groupInput).click(this.showForm.bind(this));
    $(this.body).click(this.hideForm.bind(this));
  },
  showForm: function(e) {
    e.stopPropagation();
    $(this.container).show();
  },
  hideForm: function(e) {
    if (!($(e.target).is(this.groupInput) || $(e.target).is(this.container + "," + this.container + " *"))) {
      $(this.container).hide();
    }
  }
}

我认为您需要使用keyup事件来筛选结果。。

检查这个jsfiddle

StoryGroup = {
  groupInput: '.story-group-container input[type="text"]',
  container: '.checkbox-container',
  submit: '.checkbox-container .filter',
  body: 'body',
  init: function() {
    $(this.groupInput)
      .click(this.showForm.bind(this))
      .keyup(this.onKeyup.bind(this));
    $(this.body).click(this.hideForm.bind(this));
  },
  showForm: function(e) {
    e.stopPropagation();
    $(this.container).show();
  },
  hideForm: function(e) {
    if (!($(e.target).is(this.groupInput) || $(e.target).is(this.container + "," + this.container + " *"))) {
      $(this.container).hide();
    }
  },
  onKeyup: function(e) {
    var text = $(this.groupInput).val().toLowerCase();
    $(this.container)
      .find(".checkbox")
      .hide()
      .filter(function() {
        return this.innerText.toLowerCase().indexOf(text) > -1;
      }).show();
  }
}

StoryGroup.init();