使-1在<input type =“ number” />中显示为'unlimited'

时间:2019-01-09 16:05:18

标签: html html5 input html-input

我可以根据输入的值更改HTML 的内容吗?

当输入为-1时,我希望它显示“无限制”。

运行以下代码段。

有关更多信息,请知道我正在使用Angular 7和Angular Material。

<p>When the below input value equals -1,<br/> I would like the input to display the text 'unlimited'. <br /> Is this possible? </p>

<input type="number" min="-1" />

2 个答案:

答案 0 :(得分:1)

您不能不使用欺骗手段而输入number类型的输入。

一种方法是求助于type="text"并模拟type="number"已经为您方便地完成的工作(仅允许数字输入,范围和特定于用户代理的UI)。通常结果很混乱。

另一种方法是当其输入值为-1时“隐藏”输入的数字,并通过其他方式显示文本“无限”。

我在这里通过在数字输入下方放置另一个只读输入字段来完成此操作。其他元素也可以使用,但是另一个输入字段将为您提供一致的外观。

let coolInput = document.getElementById('cool-input');

// Not sure if that covers everything
coolInput.addEventListener('keyup', handleInput);
coolInput.addEventListener('change', handleInput);
coolInput.addEventListener('paste', handleInput);

function handleInput() {
  if (coolInput.value == '-1') {
    coolInput.classList.add('unlimited');
  } else {
    coolInput.classList.remove('unlimited');
  }
}
form {
  position: relative;
}

input[type="text"],
input[type="number"] {
  color: #333;
  font-size: 16px;
  padding: 5px;
  width: 100px;
}
  
#unlimited-input {
  border: 1px solid #fff;
  position: absolute;
  z-index: -1;
}
  
#cool-input {
  background: #fff;
  border: 1px solid #999;
  opacity: 1;
}
  
#cool-input.unlimited {
  background: transparent;
  color: transparent;
}
<form>
  <input id="unlimited-input" type="text" readonly value="unlimited">
  <input id="cool-input" type="number" min="-1" placeholder="Amount">
</form>

JSFiddle

效果惊人。尚未在IE和iOS中进行测试。

答案 1 :(得分:0)

这将起作用-

$("#q").change(()=>{

if($("#q").val()==-1)
$("#w").val("unlimited")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" min="-1" id="q"/>
<input type="text" id="w"/>