问题
I'm taking data from an encrypted php script which outputs variables as e.g. %%Price%%
Annoyingly those variables are not just a decimal and numeric value.
The encrypted script renders %%Price%%
as:
<font color="green"><strong>Sale Price: $2,489.99</strong></font>
I want to strip the value of %%Price%%
to price (number and decimal) and then place that result in a hidden form field as the value.
I have tried:
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = "%%Price%%";
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>
...but this gives an empty result
回答1:
I would use:
newPrice = parseFloat(price.substring(2, price.length - 3));
回答2:
I checked your code with a jsfiddle and it seems ok. Check here: http://jsfiddle.net/CmHn6/1/. I actually replaced:
var price = "%%Price%%";
with:
var price = '<font color="green"><strong>Sale Price: $2,489.99</strong></font>';
as you said in your example. Notice that I used single quotes there. If your encrypted script does not take this into account, your line could end up like:
var price = "<font color="green"><strong>Sale Price: $2,489.99</strong></font>";
which would result in a syntax error and would not fill in your input element. If your string never use single quotes, then you can use single quotes in your code, like in my example. If not, you could put %%Price%% inside a hidden div, and read this value from there:
<div id="pricediv" display="style: none">%%Price%%</div>
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = $("#pricediv").html();
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>
来源:https://stackoverflow.com/questions/23256796/strip-data-to-number-and-decimal-then-jquery-set-input-value-to-variable