我需要验证自己的领域; 合法只是数字.
这是简单的HTML:
<div class="form-group">
<label for="superficie">Superficie</label>
<input type="text" class="form-control required-field" data-type="number" name="superficie" />
</div>
Run Code Online (Sandbox Code Playgroud)
这就是Jquery:
$('.current .required-field').each(function(index) {
$(this).keyup(function() {
var input_type = $(this).data('type');
validate($(this), input_type);
});
});
function validate(input, input_type) {
switch(input_type) {
case 'number':
if (input.value != input.value.replace(/[^0-9\.]/g, '')) {
input.value = input.value.replace(/[^0-9\.]/g, '');
}
break;
}
}
Run Code Online (Sandbox Code Playgroud)
控制台返回错误:
input.value未定义.
该input变量包含一个没有value属性的jQuery对象.要访问您需要使用的值val()方法,或者您可以为您的函数提供本机HTMLElement:
validate(this, input_type);
Run Code Online (Sandbox Code Playgroud)
最后,值得注意的是,您可以简化代码,因为它通过this以下方式挂起对元素的引用:
$('.current .required-field').keyup(validate);
function validate() {
var $el = $(this);
switch ($el.data('type')) {
case 'number':
$el.val(function(i, v) {
return v.replace(/[^0-9\.]/g, '');
});
break;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
421 次 |
| 最近记录: |