javascript - HTML input type=number 步骤阻止表单提交

标签 javascript html

我在 HTML 中有这段代码:

<input type="number" step="0.1" class="form-group">

我希望用户能够输入 3 位十进制数,例如 1.234但是step需要是 0.1它会抛出错误并阻止表单提交。

我已经试过了 step="0.100"但结果是一样的。

我还需要验证其他输入,所以我不能使用 no validate<form>标签。

需要做什么?

最佳答案

我会编写一个小的自定义内置自定义元素来实现这一点:

class MyInput extends HTMLInputElement {
  constructor(step = 0.1, value = '') {
    super();
    this.type = 'number';
    this.step = this.getAttribute('step') || step;
    this.value = this.getAttribute('value') || value;
    this.addEventListener('input', (e) => {
      this.value = parseFloat(this.value) + 0.034;
    })
  }
}

customElements.define('my-input', MyInput, { extends: 'input' });

let input = new MyInput(0.1, 1);
document.body.appendChild(input);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />

这肯定需要一些调整,例如如果用户在输入中键入内容,但这应该可以很好地作为起点。

关于javascript - HTML input type=number 步骤阻止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786140/

相关文章:

javascript - 使用对象数组等循环遍历对象数组

javascript - 使用 FileSaver.js 保存 blob

javascript - 自动将 slider 设置为默认起始值

html - 如何在文本数量后调整输入大小

javascript - 如何在另一个div中的div中的图像上放置阴影

javascript - 在多个 div 之间拆分时文本被剪裁

html - 从图像中删除背景而不添加类

javascript - 添加具有相同类的 View 复选框(Switchery)

javascript - JS 计数带千位分隔符的数字

html - Firefox 根据操作系统使用不同的内置样式表?