好的,所以我有这个任务,我不知道如何实现。我有一个文本字段,它只允许用户输入数值....我正在验证按下键,以确保只允许数字数字
效果很好
我的问题是,客户端希望文本后面的数字说"英里",所以如果用户输入100,他们看到"100英里"
我想是为了可用性。有没有人知道一个好的技术或jquery插件来做到这一点
除了javascript解决方案,您可能还想查看<input>
的HTML 5 pattern
属性。例如,在现代浏览器中,您可以这样做:
<input name="miles" pattern="^d+s?[Mm]iles$" required>
根本不需要javascript:)这是相关的规范
这个怎么样:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
我认为在文本框外的某种标记中这样做会更容易,也更清晰。有一个span直接下面或其他东西,然后更新它在你的按键。
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
这个怎么样http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/d+/g)[0]) + " Miles";
}, 2000);
}
})
});
我的问题是,客户希望文本后面的数字说:Miles"所以如果用户输入100,他们会看到"100 Miles"
那么你可以在input type="text"
的onfocus
和onblur
事件中像这样处理它。
试试这个
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
脚本
和
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
此处演示:http://jsfiddle.net/naveen/EQEMr/
告诉你的客户,任何有足够智力使用网络的人都能理解:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
和做其他事情是:
- 用户困惑
- 有问题,因为javascript可能启用或不启用/可用
- 对于业务没有任何实际用途,因为该值无论如何都必须在服务器上进行验证
- 该值需要在服务器上进行额外处理以删除附加字符