Remove Dollar Sign and Decimal Point from Input Post - javascript

I have a php form that is for processing payments and I am using js to add a dollar sign and decimal point to the input field. I can't seem to find out how I can then remove the dollar sign and decimal point on submit.
$amount = trim($_POST['amount']);
<div class="input-block">
<label for="amount" class="label_comment"><strong>Donation Amount</strong>*</label>
<input type="text" name="amount" value="<?php echo $_POST['amount']; ?>" placeholder="$" data-stripe="amount" id="amount" required="">
</div>
<script type="text/javascript" src="/js/jquery.price_format.2.0.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#amount').priceFormat({
prefix: '$',
centsSeparator: '.',
thousandsSeparator: ','
});
});
</script>

You can either use the .unmask() function to get the raw value and set in on a hidden input OR reset your formatting in the onSubmit event.
<form id="yourForm">
<div class="input-block">
<label for="amount" class="label_comment"><strong>Donation Amount</strong>*</label>
<input type="text" name="amount" value="<?php echo $_POST['amount']; ?>" placeholder="$" data-stripe="amount" id="amount" required="">
<input type="hidden" id="rawAmountField" name="rawAmount" value="" />
</div>
</form>
Two changes: a hidden field and the #id argument for the -tag. Then you can add like
<script type="text/javascript">
$(document).ready(function() {
$('#yourForm').submit(function( event ) {
/* Set the hidden field */
$('#rawAmountField').value($('#amount).unmask());
/* OR reset format like */
$('#amount').priceFormat({
prefix: '',
centsSeparator: '.',
thousandsSeparator: ''
});
});
});
</script>

I think the best way to handle this would be to use the filter_input() function. It would work like:
$filtered_amount = filter_input(INPUT_POST, 'amount', FILTER_SANITIZE_NUMBER_INT);
That would strip everything from $_POST['amount'] that isn't a numerical digit. Of course it requires the use of PHP5.2 or greater.

function remove(number) {
var tag = number.charAt(0);
if(tag=='$')
{
var res = number.slice(1);
}
if(tag!='$')
{
var res = number.slice(0);
}
document.formname.roundedfield.value = '$'+ parseInt(res);
}

Related

Php string value to input number bypass error

How to compare two input values when type is number and need get the value from a string? and why type=number can't parse values from php strings?
Error: The specified value "'.$total2.'" cannot be parsed, or is
out of range.
I found this code at this amazing answer: Enable submit button if value greater or equal to the specified value
But in this example the input get value from input.
For something reason the type=number can't handle correctly when an value stored as string is specified.
There is the code ready to copy and paste:
<?php
$total2 = "50";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
let $form = $('form');
let $total1 = $('#total1');
let $total2 = $('#total2');
let $submitButton = $(':submit');
$form.on('submit', function(event) {
let val1 = Number($total1.val());
let val2 = Number($total2.val());
if (val1 < val2) { // If condition is NOT met.
event.preventDefault(); // Default submit from happening.
return false; // Stop function.
}
});
$form.on('input', function(event) {
let val1 = Number($total1.val());
let val2 = Number($total2.val());
console.log(val1, val2)
let isDisabled = val1 < val2; // Will return true or false.
$submitButton.prop('disabled', isDisabled);
});
});
</script>
<form method="post" action="order.php">
<label for="total1">First Number</label>
<input type="number" id="total1" value="0" />
<br>
<label for="total2">Second Number</label>
<input type="number" id="total2" value="'.$total2.'" hidden />
<br>
<input type="submit" value="submit" disabled title="Not Relevant">
</form>
<?php echo $total2;?>
</body>
</html>
I can print string $total2 echo successfully.
How to bypass this?
Any hint is welcome
Thanks
PHP opening/closing tags are missing from the HTML input.
<input type="number" id="total2" value="'.$total2.'" hidden />
// should be
<input type="number" id="total2" value="<?php echo $total2; ?>" hidden />
If you don't use the opening/closing tags, PHP won't know that it should treat the $total2 code as PHP code.

Adding numbers on click with jQuery

Well, I'm trying to make a type of invoice.
Here's my problem : The invoice has various input boxes where the amount is typed by the user and there's "Total Charge"(input box) at the end of the list of those boxes. So what I want is that if some values(numeric) are filled in the the input boxes and a user click on the "Total Charge"(input box) the values are summed. How can I do it? I have used jQuery before. So, if possible can anyone explain how can I do it in jQuery?
Script so far
$('.charge').blur(function () {
var totalocharges = 0;
$('.charge').each(function() {
totalocharges += Number($(this).val());
});
$('#total_charges').val(totalocharges);
});
my view(just a part of it):
<div class="form-group col-md-offset-1 col-md-5">
<input type="number" class="charge form-control" id="amount1" name="amount1" value="<?php echo set_value('amount1'); ?>" placeholder="amount" required>
</div>
<div class="form-group col-md-offset-1 col-md-5">
<input type="number" class="charge form-control" id="amount2" name="amount2" value="<?php echo set_value('amount2'); ?>" placeholder="amount" required>
</div>
<div class="form-group col-md-offset-1 col-md-5">
<input type="text" class="form-control" id="total_charges" name="total_charges" value="<?php echo set_value('total_charges'); ?>" placeholder="net amount">
</div>
You could do something like this with jQuery.
In this example, your input boxes would have 'charge' class. And your total charge input the ID total-charges)
$('.charge').blur(function () {
var total_charges = 0;
$('.charge').each(function() {
total_charges += Number($(this).val());
});
$('#total-charges').val(total_charges);
});​​​​​​​​
Here you have a working code sample:
https://jsfiddle.net/0e8emcbu/
If you want to activate it with a button, then it would be like this:
https://jsfiddle.net/8cmL29xt/
Attach an event listener to the "Total charge" input box. For example, you can use "focus" event.
$("#total_charge").on('focus', function(){
//here you have to make calculations
//get values on all required input boxes
var value1 = $("#input_box1").val();
//another value
//sum (multiply, divide etc) values
val result = value1 + value2 + ...l
//change total_charge value
$("#total_charge").val(result);
});

Javascript load Two value single input fields

i Have created calculation Project .My code have input fields Name Estimate Property Tax . this input fields get two types of value .That Two types of value % and $ values. Now My inputs fields get % values Only .Not getting $ value.MY Old UI code:
<td>Estimate Property Tax </td>
<td>
<input name="propertytaxpc" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax; ?>" onChange="javascript:propertyTaxPcChanged(true)" />
%</td>
<td>Or $
<input name="propertytaxamt" type="text" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</td>
<td>
Now i have created this code single input value % value is default New Code:
<div class="row">
<div class="col-md-4 padding-rht bdy">
<label id="lblEstimatePropertyTax"class="pull-left"style="font-weight: 600">
Estimate Property Tax</label>
</div>
<div class="col-md-3 padding-rht">
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer"/>
</div>
MY script for ICON change:
function changeColor(event, _src) {
var fname = _src;
var ImageName = fname.substring(fname.lastIndexOf('/') + 1);
//alert(ImageName);
if (ImageName == "percent.png") {
$(event.target).attr("src", "Content/Images/RedDoller.png");
}
else {
$(event.target).attr("src", "Content/Images/percent.png");
}
}
Now MY UI i have used single input fields % and $ both value's load single input fields .Now i get % value. if i user change % to $ value also need to change. please help me i am getting % value only ? how to value change onclick function?
I'm not sure I fully understand but it appears that the value is being set server side by your php code.
value="<?php echo $dproperty_tax;?>"
using javascript to change the image doesn't go back to the server to replace the % value with the $ value. I would output two separate input fields to the DOM as you were before. But use javascript to show and hide the appropriate input box.
alternatively, you could use data attributes to hold both the percent and dollar values in the input and set the value using javascript.
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" data-percent="<?php echo $dproperty_tax;?>" data-dollar="<?php echo $TaxDollars;?>" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
then in your javascript code
var taxInput = $('input[name="propertytaxpc"]');
if (ImageName == "percent.png") {
$(event.target).attr("src", "Content/Images/RedDoller.png");
taxInput.val(taxInput.attr('data-dollar'));
}
else {
$(event.target).attr("src", "Content/Images/percent.png");
taxInput.val(taxInput.attr('data-percent'));
}

Remove dollar sign from query on Submit

I am working on a website where there is a donate box with a field and a contribute button.
<div id="donate-bar">
<form name="donate" id="donate">
<span class="donate-text">DONATE</span>
<input type="text" class="amount" name="amount" id="amount" value="$10" size="5">
<input type="submit" id="contribute" formaction="https://website.com/donate" accept-charset="utf-8" formmethod="GET" value="CONTRIBUTE">
</form>
</div>
However, the query gets sent to the donation processor's website as https://website.com/donate?amount=%2410 and doesn't tick the $10 box. If I remove the $ and submit the query again the value is sent and the correct amount is seen on the second page.
Is there an easy way using PHP or Javascript to have it remove the $ when the form is submitted so that https://website.com/donate?amount=%2410 changes to https://website.com/donate?amount=10.
I've tried a couple of things but nothing I've tried has worked. Some examples of code would be super helpful since I'm newer to some of this. Can I parse it as integer on submit? Any help would be greatly appreciated. Thank you!
Why not put the Dollar sign outside of the input and store the value as "10":
<div id="donate-bar">
<form name="donate" id="donate">
<span class="donate-text">DONATE</span>
$<input type="text" class="amount" name="amount" id="amount" value="10" size="5">
<input type="submit" id="contribute" formaction="https://website.com/donate" accept-charset="utf-8" formmethod="GET" value="CONTRIBUTE"></form></div>
$('form#donate').on('submit',function() {
var $input = $('input#amount');
$input.val(parseInt($input.val().replace(/\$/,''),10));
});
$_POST['amount'] = str_replace("$", "", $_POST['amount']);
There is a simple way to fix this.
First of all, one of my suggeestions is that you change the field to
type="number"
Second of all, in PHP, you can use the following to remove the dollar sign:
$amount = str_replace('$', '', $_REQUEST['amount']);
You can use split function in jquery as follows
var value = ($('#amount').val()).split('$');
var amount = value[1] ;
In PHP
$value = explode('$',$_POST['amount']); //results array elements
without $ symbols $amount = $value[1];
Or also in PHP
$amount = preg_replace("/[^0-9]/","",$_POST['amount']);
//gets only integer parts and omits all other
Also in PHP
$amount = str_replace('$', '', $_POST['amount']);
Hope this helps the simplest way is a hidden field:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
//number regex - the format $10
var regex = /\$[1-9][0-9]+/;
//Setting validations
$(document).on('blur', '#pretty_amount', function() {
if(!regex.test($(this).val())) {
//Do something probably clear field
alert("Error Invalid number: " + $(this).val());
} else {
var newValue = $(this).val().match(/[1-9][0-9]+/g);
$('#amount').val(newValue);$('#amount').innerHtml(newValue);
}
});
});
</script>
</head>
<body>
<div id="donate-bar">
<form name="donate" id="donate">
<span class="donate-text">DONATE</span>
<input type="text" style="display: none;" name="amount" id="amount">
<input type="text" class="amount" name="pretty_amount" id="pretty_amount" value="$10" size="6">
<input type="submit" id="contribute" formaction="https://website.com/donate" accept-charset="utf-8" formmethod="GET" value="CONTRIBUTE"></form></div>
</body>
</html>
This does what you want, if I'm not mistaken.
Best regards

JavaScript error in function which calcs sum of two values

this is my JS code to check the match of two digits
<script type="text/javascript">
function match(){
var a=parseInt(document.getElementById("one"));
var b=parseInt(document.getElementById("two"));
var c=parseInt(document.getElementById("sum"));
var d;
d=a+b;
if(d!=c)
{
alert("Something is wrong!!");
}
else
{
alert ("Success");
}
}
</script>
html code for generat two digits and check on the process.
<form action="#" method="post" onsubmit="return match();">
<input type="text" name="one" id="one" value="<?php echo rand(1,9); ?>" readonly="readonly"/>
+
<input type="text" name="two" id="two" value="<?php echo rand(1,9); ?>" readonly="readonly"/>
=
<input type="text" name="sum" id="sum" />
<input type="submit" value="submit" />
</form>
Perhaps you want their value and not the element itself.
var a=parseInt(document.getElementById("one").value,10);
var b=parseInt(document.getElementById("two").value,10);
var c=parseInt(document.getElementById("sum").value,10);
Also, provide the radix when you are using parseInt() otherwise it may go crazy sometimes.

Categories