用输入jQuery的.val()计算

Pau*_*aul 1 html javascript jquery

我正在研究一个项目,我必须对输入字段的现有值进行一些计算.让我们说输入值是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>
Run Code Online (Sandbox Code Playgroud)

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 */   
        }

    });
});
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

priceTag.val(+ 425);
/* And more of this type of wrong code ;-P */
Run Code Online (Sandbox Code Playgroud)

我试图查找现有的例子,但我没有找到很多例子,所以提前感谢答案!

Ror*_*san 6

这个逻辑有点复杂.您需要知道在单击425之前no是否已添加,在这种情况下您需要减去425,而不仅仅是添加0.

考虑到这一点,您可以data在输入中添加一个属性以包含它的起始价格:

<input id="priceTag" name="priceTag" type="text" value="400" data-default="400">
Run Code Online (Sandbox Code Playgroud)

然后,当select更改时,您可以将data属性转换为整数,然后对其执行计算.试试这个:

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'));
        }        
    });
});
Run Code Online (Sandbox Code Playgroud)

示例小提琴