javascript - 如何隐藏 html 输入列表中的某些字符?

标签 javascript css html input datalist

我有一个 html 输入列表,以及一个关联的数据列表,定义如下:

<input list="mylist" id="my-input" name="friend-name" 
   placeholder="Begin typing friend's name here..." 
   required class="form-control">

列表本身(和关联的数据列表)工作正常。但是,我的每个条目都是以下形式:"String [numeric_id]"

  • 我想知道是否有任何方法可以隐藏 提交表单之前的 [numeric_id] 部分。
  • 我查看了 pattern 属性,但这似乎限制了 输入中允许的实际数据,这不是我想要的 - 我只是 想要隐藏方括号 [] 之间的部分,但仍然 提交表格。
  • 也可以将其移动到 type=hidden 的另一个输入。 有什么可行的方法吗?

@isherwood,这是我的表单标签:

<form action="/chat_forwarding/modal_edit_msg.php" id="fwd-form" method="POST" class="form-inline" style="display: block;">

最佳答案

如果您没有使用任何支持绑定(bind)的框架,您应该监听输入事件并根据它更新隐藏的输入。

这是一个可能会给你思路的函数:

let realInput = document.getElementById('real-input');
let userInput = document.getElementById('user-input');
userInput.addEventListener('input', function(value) {
  const inputValue = value.target.value;
  realInput.value = inputValue; // update the hidden input
  const userInputResult = inputValue.match(/\[[^\[]*\]/); // the regex for [numberic_id]
  if (userInputResult) {
    userInput.value = inputValue.substring(0, [userInputResult.index - 1]); // -1 is to remove the space between the 'string' and the '[numeric_id]'
  }
});

关于javascript - 如何隐藏 html 输入列表中的某些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261700/

相关文章:

jquery - 滑动 div 内容

javascript - 如何检测字符串中的单位?

javascript - d3 我希望隐藏网格线溢出

javascript - 为动态生成的 div 多次调用单击操作

javascript - 单击按钮时如何显示我的定价表?

javascript - 将日期选择器的值传递给函数

javascript - 在标题中插入和删除字符/单词

asp.net - 如何确定 JavaScript 中 RadioButtonList 的 SelectedValue?

javascript - 在 PhantomJS 上我不能包含 jQuery 并且没有 jQuery 我不能发布表单数据

css - 网页顶部的额外空白