Reputation: 3
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
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
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
Hope this helps
Upvotes: 1
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