繁体   English   中英

input.value未定义

[英]input.value is undefined

我需要验证自己的领域; 合法只是数字。

这是简单的HTML:

<div class="form-group">
    <label for="superficie">Superficie</label>
    <input type="text" class="form-control required-field" data-type="number" name="superficie" />
</div>

这就是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;
        }
    }

控制台返回错误:

input.value未定义。

input变量包含一个没有value属性的jQuery对象。 要访问您需要使用val()方法的值,或者您可以为函数提供本机HTMLElement:

validate(this, input_type);

最后,值得注意的是,您可以简化代码,因为它通过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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM