Shadab akhtar
Shadab akhtar

Reputation: 3

setting auto decimals at input box in jquery not working

Hi everyone i am new in jquery i created some input box and want when some one enters some value or the input get value for database it will automatically add decimal upto 2 i applied this code but it is not working kindly help me

         ?>
         <script type="text/javascript">
         function setTwoNumberDecimal(event) {
        this.value = parseFloat(this.value).toFixed(2);
          }
         </script>
         <?
  print '<tr><td>';
	print fieldLabel('Others Deductions','other_deduction',1).'</td><td>';
	print '<input  class="sub"  onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="'.GETPOST("other_deduction").'">';
	print '</td></tr>';

Upvotes: 0

Views: 592

Answers (3)

moni_dragu
moni_dragu

Reputation: 1163

Your problem is you are passing an object to your javascript function (which is correct) but are not using it like you should.

The code should look like this:

      function setTwoNumberDecimal(obj) {
        obj.value = parseFloat(obj.value).toFixed(2);
          }
  <tr>
  <td>Others Deductions</td>
  <td>
<input type="text" class="sub" onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="" />
  </td>
</tr>

Upvotes: 0

Geeky
Geeky

Reputation: 7496

Check the following code snippet

$(document).ready(function(){
  $("#text1").bind('change',function(){
    var value=$(this).val();
    $(this).val(parseFloat(value).toFixed(2));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1" />

Hope this helps

Few suggestions

  1. Never mix your markup with javascript. Try binding your events change/click at javascript end
  2. In your setvalue method code, your passing event as parameter and trying to access this.value, this here would refer to window object

Hope this helps

Upvotes: 1

AHJeebon
AHJeebon

Reputation: 1248

Everthing is okay, just use event inside function instead of this.

Testting purpose pure html code and your code:

  function setTwoNumberDecimal(event) {
    event.value = parseFloat(event.value).toFixed(2);
  }
<input type="text  class="sub"  onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="">

<script type="text/javascript">
    function setTwoNumberDecimal(event) {
    event.value = parseFloat(event.value).toFixed(2);
  }
  </script>
<?php    print '<tr><td>';
	print fieldLabel('Others Deductions','other_deduction',1).'</td><td>';
	print '<input  class="sub"  onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="'.GETPOST("other_deduction").'">';
	print '</td></tr>';
?>

Upvotes: 0

Related Questions