Strip data to number and decimal then jquery set input value to variable

那年仲夏 提交于 2019-12-13 18:11:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!