Replace dots and commas in a field and then use that value to auto populate another field using jquery

1.3k Views Asked by At

I'm using Google Maps to calculate distance between cities. I need to use that distance value for some basic calculations. Distance has to be in "Angloamerican" format (1,234.00) but in metric system. So, Google Maps answer for Madrid - Berlin query will be one of these two:

a) <span jscontent="distance['text']" jsdisplay="distance" jstcache="7">2.320,1 km</span>
b) <span jscontent="distance.text" jstcache="23">2.320,1 km</span>

Please notice the differences in span "classes" (jstcache is 7 or 23) and lack of any "id" or "name" attributes.

What I want to accomplish is:

1) Convert these Google Maps distance values to "Angloamerican" format (2,320 km) or (even better) format without thousands separator which would only use dots as decimal separator (2320.1 km)

2) Use that filtered value to populate a text field called distance

I searched all over the web, but didn't find the exact answer. This post was the most helpful:

Populate hidden form element value with the value of a text field on form submit (jQuery)

It helped me a bit with the auto-populate part, but I can't make it work in combination with this Google Maps code. Here is my current code:

<head>
...
<script type="text/javascript">
function submitMyForm(){
$('#distance').val($('jstcache^=7').val());
$('#Googlemap').submit();
}
</script>
...
</head>

<body>
...
<form id="myform">
<input type="text" id="distance" name="distance" value="" />
</form>
...
</body>
2

There are 2 best solutions below

7
On

To grab the value:

var dist = $('span[jstcache=7]').val();

To localize:

var parts = dist.split(',');
dist = parts[0].replace('.','') + '.' + parseInt(parts[1],10);
3
On

Generally, you can do this with the javascript string .replace() function. In this case, it's a little trickier because you're doing a swap: periods for commas, commas for periods. This means you have to use an intermediate value. A working example using underscores would be something like this:

<script type="text/javascript">
function submitMyForm(){
    var val = $('[jstcache=7]').text(); // get text content of <span jstcache="7">

    // Replace using regex instead of strings, to catch more than the first match
    val = val.replace(/\./g, "_");
    val = val.replace(/,/g, ".");
    val = val.replace(/_/g, ",");

    $('#distance').val(val);
    $('#Googlemap').submit();
}
</script>