简体   繁体   中英

input.value is undefined

I need to validate myself a field; legit are only number.

This is the simple 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:

$('.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.

The input variable contains a jQuery object which has no value property. To access the value you need to use the val() method, or you could provide the native HTMLElement to your function:

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 :

$('.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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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