Anu*_*jan 16 html javascript jquery
我希望每当更改另一个的值时更改输入字段的值.
我已经尝试了一段时间,我似乎无法让它工作
<input class="span4 input-big" id="dare_price" name="price" size="30" type="text" onChange="updatePrice()" />
<input class="span4 input-big" id="total_price_amount" readonly="readonly" value=""/>?
function updatePrice() {
var price = $("#dare_price").val();
var total = (price + 1) * 1.05;
$("$total_price_amount").val(total);
}?
Run Code Online (Sandbox Code Playgroud)
OAC*_*gns 12
有几件事.
首先,如果我是你,我会使用最新版本的jQuery.我们现在在1.8.
我还使用"keyup"作为事件触发器以及"更改".它在我看来更有用.我也喜欢使用jQuery绑定事件.见http://api.jquery.com/on/
您的代码中存在一些错误.注意该$("$total_price_amount")
部分抛出错误
如果只想显示设定的小数点数,请使用.toFixed()
.但请注意,这将返回一个字符串.
来自文本框的输入值是类型string
,因此要使用它们进行数学计算,您需要将它们解析为a int
或afloat
http://jsfiddle.net/DigitalBiscuits/QWSQp/71/
$(document).ready(function()
{
function updatePrice()
{
var price = parseFloat($("#dare_price").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total_price_amount").val(total);
}
$(document).on("change, keyup", "#dare_price", updatePrice);
});
Run Code Online (Sandbox Code Playgroud)
请注意,我已从onChange="updatePrice()"
HTML中删除了该部分,因为它不再需要.
希望这对你有所帮助.
$("#dare_price").change(function(){
var total = Number($this).val()) + ...;
$('#total_price').val(total);
});
Run Code Online (Sandbox Code Playgroud)
如果您以编程方式更改了值,则需要通过方法对它们进行流水线处理-
function changePrice(value){
$('#dare_price').val(value);
$('#dare_price').trigger('change');
}
Run Code Online (Sandbox Code Playgroud)
针对此事件驱动方法更新了DEMO。
归档时间: |
|
查看次数: |
51846 次 |
最近记录: |