Number.prototype.function does not work with jQuery (..) result. Val ()

I took this piece of code from another post.

Number.prototype.countDecimals = function () {
    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
    return this.toString().split(".")[1].length || 0; 
}

var x = 23.453453453;
x.countDecimals(); //returns 9 as expected

      

Basically, it returns the number of decimal places in a given number. The problem is, I need to get this value from a number that is inside the input:

console.log($('#myinput').val().countDecimals());

      

... but this action returns: Uncaught TypeError: undefined is not a function

How can I integrate the previous code to work with input values ​​(using jQuery)? Thank!

+3


source to share


3 answers


You are defining a function countDecimals

in the object prototype Number

, so it can only be called on objects of the type Number

. I have not tested this, but you can use instead Number($('#myinput').val()).countDecimals()

.



+2


source


This is because .val()

actually returns an object: Object [value]

. Just do parseFloat

on it:



console.log( parseFloat( $('#myinput').val() ).countDecimals() );

      

+2


source


it will give the desired result,

 <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type ="text" id="inpVal">
<input type ="button" id="inpBtn" value="click!!!!">
<script>
Number.prototype.countDecimals = function () {
    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
    return this.toString().split(".")[1].length || 0; 
}

$("#inpBtn").click(function(){
    var x = parseFloat($("#inpVal").val()).countDecimals();
    alert(x);
});
</script>
</body>
</html>

      

+2


source







All Articles