简体   繁体   中英

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. For example, if I click the answer_1 radio it will add 1 to the variable making it 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.

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. 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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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