【问题标题】:Put two or more values to one input (number field)将两个或多个值放入一个输入(数字字段)
【发布时间】:2020-10-04 07:09:55
【问题描述】:

我有一个数字类型的输入字段...

我想要这种格式:

年龄-身高-体重

20-180-80

如何强制用户输入该类型,然后将最终结果插入输入字段 type="number" 并提交?

年龄 - 从 16 岁到 99 岁 身高——从 100 到 290 重量——从 40 到 200

那么结果,例如 18-170-60 必须作为一个值发送...

【问题讨论】:

  • 顾名思义,type="number" 的输入只能有一个数字作为值。您在此处描述的是您要对其应用验证的text 类型的输入
  • 20-180-80 这是文本而不是数字。所以你不能用数字输入来做到这一点
  • 好的,文本字段怎么办?

标签: javascript html jquery css node.js


【解决方案1】:

您可以通过使用电话 html 输入来解决此问题,而不是使用一些正则表达式来获取您想要的格式。这是解决方案的sn-p

注意:Safari 10 或更早版本不支持模式标签,以支持您希望通过 javascript 完成正则表达式

var sub = document.getElementById("submit");
var input = document.getElementById("userinfo");
sub.onsubmit = function() {
	var args = input.value.split("-");
    if (args[0] < 16 || args[0] > 99) { invalidInput("age"); return; } 
    if (args[1] < 100 || args[1] > 290) { invalidInput("height"); return; }
    if (args[2] < 40 || args[2] > 200) { invalidInput("weight"); return; }
    console.log(`Age: ${args[0]}, Height: ${args[1]}, Weight: ${args[2]}`);
}
function invalidInput(type) {
    console.log(`Input "${type}" was invalid`);
    return;
}
<!DOCTYPE html>
<html>
<body>

<form id="submit">
  <label for="userinfo">Info:</label>
  <input type="text" id="userinfo" placeholder="Age-Weight-Height" pattern="[0-9]{2}-[0-9]{3}-[0-9]{2,3}" title="Three, Three digit numbers, separated by hyphons e.g. 123-123-123"><br><br>
  <input type="submit">
</form>

</body>

</html>

【讨论】:

    【解决方案2】:

    你基本上可以这样做。使用模式进行基本验证,使用验证进行附加验证。它还不完美(并且没有错误),但它应该给你一个好的方向。

    let input = document.querySelector("#age-height-weight");
    
    function validate() {
      let regex = /(\d+)-(\d+)-(\d+)/
      let content = regex.exec(input.value);
      input.setCustomValidity("");
      
      // This validation is done implicitly using 'pattern' and 'required', 
      // but you could also do this manually, which would be actually more consistent.
      if (!content) return;
      
      // Now the additonal validation, if the pattern basically is fine.
      let [all, age, height, weight] = content;
      if (age < 16 || age > 99) {
        input.setCustomValidity("Invalid age.")
      }
      if (height < 100 || height > 290) {
        input.setCustomValidity("Invalid height.")
      }
      if (weight < 40 || weight > 200) {
        input.setCustomValidity("Invalid weight.")
      }
    }
    
    input.addEventListener("focusout", validate);
    input.addEventListener("focusin", validate);
    <form id="my-form">
      <input type="text" id="age-height-weight" pattern="\d{2}-\d{3}-\d{2,3}" title="Age (16-99)-Height (100-290)-Weight (40-200)" required>
      <button type="submit">Submit</button>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多