简体   繁体   English

在Javascript中使用更改事件添加或减去值

[英]Add or Subtract Values with change event in Javascript

I have the following code: 我有以下代码:

//code not relevant to question 

var answer_1 = parseInt(3),
    answer_2 = parseInt(1),

$radioOptions.on("change",function(){
 //additional code

    answer_1 = answer_1 + 1;

 //more code

    answer_2 = answer_2 + 1;

});

What happens is when a radio is clicked within a form we add 1 to that var. 当在表格中单击单选按钮时,会发生这种情况,我们在该变量中添加1。 For example, if I click the answer_1 radio it will add 1 to the variable making it 4. 例如,如果我单击answer_1单选按钮, answer_1在变量中加1,使其变为4。

Here is the problem I run into. 这是我遇到的问题。 There are multiple radio options. 有多个收音机选项。 If a person clicks answer_1 then clicks answer_2 it adds 1 to both fields as they have clicked both fields. 如果某人单击了answer_1 然后单击了answer_2则由于他们单击了两个字段,因此会将两个字段都加1。

What I need to do is only add the one for the option they choose. 我需要做的只是为他们选择的选项添加一个。 In other words, if they click answer_1 it adds plus 1 to that variable. 换句话说,如果他们单击answer_1则会向该变量加1。 If they then choose answer_2 it removed the plus 1 from the one they previously selected and adds plus one the the now selected option. 如果他们然后选择answer_2则会从以前选择的选项中删除加号1,并在现在选择的选项中添加加号1。

How would I achieve this? 我将如何实现?

Try this: 尝试这个:

 var selector = $('input[type=radio]'); var preElem; selector.on('change', function () { ++this.value; if (preElem) { --preElem.value; $(preElem).parents('label').next().text(preElem.value); } preElem = this; $(this).parents('label').next().text(this.value); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label for="1"> <input type="radio" id="1" name="test" value="1">Radio 1</label>&nbsp;&nbsp;Total: <span>1</span> <br> <label for="2"> <input type="radio" id="2" name="test" value="1">Radio 2</label>&nbsp;&nbsp;Total: <span>1</span> <br> <label for="3"> <input type="radio" id="3" name="test" value="1">Radio 3</label>&nbsp;&nbsp;Total: <span>1</span> <br> <label for="4"> <input type="radio" id="4" name="test" value="1">Radio 4</label>&nbsp;&nbsp;Total: <span>1</span> <br> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM