javascript - 使用输入 jQuery 的 .value() 计算

标签 javascript jquery html

我正在做一个项目,我必须对输入字段的现有值进行一些计算。假设输入值为 400 或其他值。

下面我有一个选择框 YES 表示添加 425NO 表示添加 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'));
        }        
    });
});

Example fiddle

关于javascript - 使用输入 jQuery 的 .value() 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26976650/

相关文章:

javascript - MVC C# Redirect() 到字符串 url 不起作用

javascript - 将对象数组转换为对象

javascript - 如何判断一条消息是否为回复,并查看回复的消息内容? (discord.js)

.show 的 JQuery 事件监听器 ('drop' , 500) == 完成

html - 用于定位变量 ID 名称的 CSS

javascript - 清除 HTML5 文件系统 API

javascript - 使用 Javascript 对 HTML 表格进行排序

javascript - Chrome 和 safari 无法正确呈现 div

javascript - 启用/禁用组合选择的文本框

html - 使用渐变颜色和多个 div 构建的 css 彩虹