[英]Validate user input with whitespace
如何實時格式化用戶輸入? 例如,用戶將A9364470240ZGS001
放入輸入字段,並在輸入字段中實時使用 JavaScript 格式為: A 936 447 02 40 ZGS 001
?
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}">
</div>
如果我們假設用戶必須一個一個地寫字符。 這將起作用。
<body>
<input type="text" class="form-control" id="ds" name="ds" onkeypress="keyPress()" maxlength="23">
</body>
<script>
function keyPress() {
var field = document.getElementById("ds");
var text = field.value;
if(text.length == 1 || text.length == 5
|| text.length == 9 || text.length == 12
|| text.length == 15 || text.length == 19 ) {
var newText = text + " ";
field.value = newText;
}
}
</script>
我找到了真正的答案。 如果您願意,這些期望被命名為“輸入掩碼”。 您必須使用 3. 方庫。 其中一些在以下網站中列出:
我為您的問題選擇了Cleave.js
。 這是演示:
<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<script src="https://nosir.github.io/cleave.js/dist/cleave-phone.i18n.js"></script>
<script>
function loadFunction() {
// custom
var cleaveCustom = new Cleave('.input-custom', {
blocks: [1, 3, 3, 2, 2, 3, 3],
delimiter: ' ',
});
}
</script>
<body onload="loadFunction()">
A 936 447 02 40 ZGS 001
<div class="container">
<input class="input-custom" placeholder="Custom delimiter & blocks" />
</div>
</body>
這是一個小例子。
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds">
</div>
<div class="test_ds"></div>
JS 與 jquery。
$("#ds").change(function(){
var ds_value = $("#ds").val();
var temp = ds_value;
temp = temp.substring(0,1) + " " + temp.substring(1, 4) + " " + temp.substring(4, 7) + " " + temp.substring(7, 9) + " " + temp.substring(9, 11) + " " + temp.substring(11, 14) + " " + temp.substring(14, 17);
$("#ds").val(temp);
$(".test_ds").html(temp);
});
首先,您需要在輸入中添加 onchange="getTimeNow()" oninput="getTimeNow()"
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}" onchange="getTimeNow()" oninput="getTimeNow()">
最后,您將獲得事件輸入文本
<script>function getTimeNow(){console.log(new Date())}</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.