Microsoft Excel
Microsoft Excel

Reputation: 159

jQuery .val() ignoring trailing decimal points

I am currently working on limiting the allowed input in a numeric text field. I check the length of the value of the input field, if it is >= to the maxlength attribute, don't input anything.

$('input[maxlength]').on('keyup', '', null, function(event) {
    var ref = $(this),
        val = ref.val();
    if ( val.length >= this.maxLength && event.which != 8){
        return false;
    }
}

However, if the currently value of the field ends in a decimal (eg "4."), then the val() method returns "4", which throws off the whole process. How can I read the contents of the input field while including the trailing decimal points?

http://jsfiddle.net/n3fmw1mw/329/ (Type in '4.' and you'll see what I'm talking about.)

EDIT: I've tried something from Mr. Hill's suggestion and now I have this

$('input[maxlength]').on('keydown', '', null, function(event) { //enforce maxlength on all inputs, not just text inputs
    var ref = $(this);
    ref.attr('type','text');
    var val = ref.val();

    if ( val.length >= this.maxLength  && event.which != 8){
        ref.attr('type','number');          
        return false;
    }
    ref.attr('type','number');   
});

But now nothing is being inserted into my text box, even if debugging and seeing that we aren't returning false.

Upvotes: 2

Views: 1706

Answers (1)

James Hill
James Hill

Reputation: 61793

The decimal is being dropped because your input type is number. Set your input type to text.

<input type="text" id="textbox1"/>

Here's a working fiddle.

EDIT

Based on your new requirement of not being able to change the source, the code below should get you pointed in the right direction.

jQuery does not allow you to change the type of an element. To do it, you must remove the element and add one of the correct type in its place. The code below does just that.

Note: In an effort to make the code more reusable, I added a class to your element and then edited all elements with that particular class.

// Add class to identify that element type needs changed
$("#textbox1").addClass("numberToText");

// Swap number type input with text
$('.numberToText').each(function() {
  $("<input type='text' />").attr({
    id: this.id,
    name: this.name,
    value: this.value
  }).insertBefore(this);
}).remove();

$("#textbox1").keyup(function() {
  $('#log').append("Value: " + $('#textbox1').val() + '<br/>');
});

$(".button").click(function() {
  $('#log').append("Value: " + $('#textbox1').val());
})

Here's a working fiddle.

Upvotes: 4

Related Questions