8X3ETcA7fqD
8X3ETcA7fqD

Reputation: 47

How do I add a certain number each time when click?

I have var i = 14, and button that increment i++.

When I click on the button I have added every time +1. Example 14, 15, 16, 17.

I want to do step not in with 1 but with 14. Example 14, 28, 42?

https://jsfiddle.net/xLwDgZODc/zkont5d4/

var i = 14;

$('.click').click(function() {
  $('.result').text(i++);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class='result'></span>
<button class="click">Click</button>

Upvotes: 1

Views: 335

Answers (5)

connexo
connexo

Reputation: 56754

Just to add an alternative option, you could use <input type="number" /> as it offers exactly the functionality you want using the step attribute:

<input type="number" value="14" step="14" />

Then, if you want a variable that is updated with every increase/decrease, just add an eventListener:

var i;

stepper.addEventListener('input', () => { i = result.textContent = stepper.value; console.log(i); })
<input type="number" value="14" step="14" id="stepper" />
<span id="result">14</span>

Upvotes: 1

Adnane Ar
Adnane Ar

Reputation: 683

I think that you want to increase the i variable by +1 each time until it's higher or equal to 14 then it starts to increase by +14. Here is a script that i've made for your problem, hope you enjoy it!

var i = 0;

$('.click').click(function() {
  i < 14 ? i++ : i += 14;
  $("#counter").text(i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="counter">0</span>
<button class="click">Click</button>

Upvotes: 0

King David
King David

Reputation: 1

var i = 14;

$('.click').click(function() {
    $('.result').text(i += 14);
});
//Since your increment is by 14 i+=14

Upvotes: 0

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

Simple add your step to i , see below fiddle :

var i = 14;
var step = 14;

$('.click').click(function() {
	 $('.result').text(i);
     i += step;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="click">click</button><br />
Result :<div class="result">
  
</div>

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

You could add the wanted value to the variable.

var i = 14;

$('.click').click(function() {
    $('.result').text(i += 14);
});

Upvotes: 4

Related Questions