简体   繁体   English

input.value未定义

[英]input.value is undefined

I need to validate myself a field; 我需要验证自己的领域; legit are only number. 合法只是数字。

This is the simple HTML: 这是简单的HTML:

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

And this is the Jquery: 这就是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;
        }
    }

Console returns me the error: 控制台返回错误:

input.value is undefined. input.value未定义。

The input variable contains a jQuery object which has no value property. input变量包含一个没有value属性的jQuery对象。 To access the value you need to use the val() method, or you could provide the native HTMLElement to your function: 要访问您需要使用val()方法的值,或者您可以为函数提供本机HTMLElement:

validate(this, input_type);

Finally, it's worth noting is that you can simplify your code as it all hangs off the reference to the element via this : 最后,值得注意的是,您可以简化代码,因为它通过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