Adding 0 to the decimal entered in the input?

I am trying to end a quick form using jQuery, which should add 0 to the decimal point if the decimal character is the first char entered in the input.

For example, .25 would be 0.25 before submitting the form. However, 2.05 will remain at 2.05, and 0 will not be added.

Is there a simple function here that could help me? I would rather write something long and detailed if it is not needed.

Also, here is the input box I am asking for help for reference

<input type="number" name="dailygain" id="dailygain" /> 
+4
source share
5 answers

You can use parseFloat to format floating point numbers.

 var el = document.getElementById("dailygain"); el.value = parseFloat(el.value); 
+9
source

Multiply by 1 ( *1 ) to make it numeric.

If you make it a number, he will do it automatically for you; formatting based on the locale of your system.

Example:

 var x = '.25'; console.log( x*1 ); // 0.25 

The same can be done with a unary plus (e.g. console.log( +x ); )

+1
source

parseFloat is probably more suitable, but anyway:

 $('#dailygain').on('keyup', function() { if (this.value[0] === '.') this.value = '0'+this.value; }); 

Fiddle

0
source

Put this in the run onsubmit function.

 var num=$("#dailygain").val(); //read the number from the textbox num=num.toString(); //convert that number to a string if (num.charAt(0)==".") //check if the string starts with a period num="0"+num; //if so, add a 0 in front of it $("#dailygain").val(num); //write the number back to the tb 
0
source
 $("input[name=dailygain]").keyup(function(){ var val = this.value; if(val.charAt(0) === '.'){ this.value = ('0'+val); } }); 

http://jsbin.com/ofivun/2/edit

0
source

Source: https://habr.com/ru/post/1412296/


All Articles