我正在做一个项目,我必须对输入字段的现有值进行一些计算。假设输入值为 400 或其他值。
下面我有一个选择框 YES 表示添加 425,NO 表示添加 0 或减去-425;
HTML:
<input id="priceTag" name="priceTag" type="text" value="400">
<select id="designChoice" name="designChoice">
<option>Choose--</option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
jQuery:
jQuery(document).ready(function($){
var priceTag = $('#priceTag');
$('#designChoice').on('change', function(){
if($(this).val()==='yes'){
/* Here i want to add + 425 to the */
}else{
/* Here I want to add nothing to the input or substract -425 */
}
});
});
我尝试过的:
priceTag.val(+ 425);
/* And more of this type of wrong code ;-P */
我已尝试查找现有示例,但没有找到很多示例,因此在此先感谢您的回答!
最佳答案
这个逻辑有点复杂。您需要知道在单击no
之前是否已经添加了425
,在这种情况下您需要减去425
,而不仅仅是添加0
。
考虑到这一点,您可以向输入添加一个 data
属性以包含它的起始价格:
<input id="priceTag" name="priceTag" type="text" value="400" data-default="400">
然后当 select
改变时,您可以将数据属性转换为整数,然后对其执行计算。试试这个:
jQuery(document).ready(function ($) {
var $priceTag = $('#priceTag');
$('#designChoice').on('change', function () {
if ($(this).val() === 'yes') {
$priceTag.val(parseInt($priceTag.data('default'), 10) + 425);
} else {
$priceTag.val($priceTag.data('default'));
}
});
});
关于javascript - 使用输入 jQuery 的 .value() 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26976650/