John
John

Reputation: 261

jQuery to change value on submit

I have a problem by using a PayPal donation-button.

The currency format for PayPal is defined with a dot. In europe our currency uses comma. This causes a problem where after submitting the form PayPal says that there is a wrong format for the amount.

Usually it would not be an issue to simply use str_replace(',','.', $_POST['amount']) but the form will be send directly to PayPal so that there is no chance to validate/replace the input by using php.

That is why I need to use jQuery.

The basic idea is to check if there is a comma in the value and in case just replace the comma with a dot and return true to post the form.

$(function() {
    $('#paypal').submit(function() {
           if ($('#amount') contains a comma) {
              replace comma with dot;
           }
      }
        return true; 
    });
});

I usually don't use jQuery. So if there is some who could help me out I really would appreciate.

Thanks in advance.

Upvotes: 0

Views: 739

Answers (3)

er_Yasar
er_Yasar

Reputation: 160

You can use replace all the occurrences of comma to dot.

if ($('#amount').val().indexOf(',')!=-1) {
      $('#amount').val()=$('#amount').val().replace(/,/g,'.')
}

Upvotes: 1

Tushar
Tushar

Reputation: 87233

You can use replace() with regex if there will be multiple , in the amount.

$(function() {
    $('#paypal').submit(function() {
        $('#amount').val($('#amount').val().replace(/,/g, '.'));
        return true;
    });
});

g flag will make sure that all occurrences of , are replaced.


If there will be only one , you can use replace without regex(faster)

$('#amount').val($('#amount').val().replace(',', '.'));

Upvotes: 4

Bhavin Solanki
Bhavin Solanki

Reputation: 4828

You can use String replace() Method.

var str = '190,89';
var res = str.replace(",", "."); 

Upvotes: 0

Related Questions