将数据剥离为数字和小数,然后jQuery将输入值设置为变量 [英] Strip data to number and decimal then jquery set input value to variable

查看:105
本文介绍了将数据剥离为数字和小数,然后jQuery将输入值设置为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个加密的php脚本中获取数据,该脚本输出变量,例如%%Price%%

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.

加密的脚本将%%Price%%呈现为:

<font color="green"><strong>Sale Price: $2,489.99</strong></font>

我想将%%Price%%的值剥离为价格(数字和小数),然后将结果放置在隐藏的表单字段中作为值.

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.

我尝试过:

<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

推荐答案

我用jsfiddle检查了您的代码,看来还可以.检查此处: http://jsfiddle.net/CmHn6/1/.我实际上替换了:

I checked your code with a jsfiddle and it seems ok. Check here: http://jsfiddle.net/CmHn6/1/. I actually replaced:

var price = "%%Price%%";

具有:

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>";

这将导致语法错误,并且不会填写您的输入元素. 如果您的字符串从不使用单引号,则可以像我的示例一样在代码中使用单引号. 如果没有,您可以将%% Price %%放在隐藏的div中,然后从那里读取该值:

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>

这篇关于将数据剥离为数字和小数,然后jQuery将输入值设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆