Martin Kolarov
Martin Kolarov

Reputation: 61

Decrease variable by 1 Javascript

<input type='text' maxlength='32' onkeypress='previewLength(32)'>

I want to decrease 32 with 1 each time a key is pressed

Im using this for a length preview (max length is 32 and each time a key is pressed it gets decreased by 1 and shows the user how much he has left)

<script>
function previewLength (maxLength) {
maxLength = maxLength -= 1;
document.getElementById('CounterLength').innerHTML = maxLength;
}
</script>

Upvotes: 0

Views: 2844

Answers (3)

vittore
vittore

Reputation: 17579

I would add some check not to show negative number, and just pass name of the control

window.updateCounter = function updateCounter(e, name) {
  var len = e.value.length
  , max = e.maxLength
  , remaining = (max - len) > 0 ? max-len : 0
  document.getElementById(name).innerHTML = remaining
}

markup

<input type='text' maxlength='32' onkeypress='updateCounter(this, "counter")'/>
<span id='counter'>32</span>

Upvotes: 0

Guffa
Guffa

Reputation: 700402

Use the length of the actual value instead of counting keypresses (as for example the backspace key would reduce the length instead of increasing it):

<input type="text" maxlength="32" onkeypress="previewLength(this.maxLength, this.value.length, 'CounterLength');">

<script type="text/javascript">
function previewLength (maxLength, actualLength, id) {
  document.getElementById(id).innerHTML = maxLength - actualLength;
}
</script>

(By also sending the maxlength and display element id into the function, it can be reused for multiple elements.)

Upvotes: 2

Halcyon
Halcyon

Reputation: 57729

You have some misconceptions, you'll want to look at the actual value, not the number of keypresses. For example: backspace, and arrow-left are also keypresses but they don't increase the length of the value.

html:

<input type='text' maxlength='32' onkeypress='previewLength(this, 32)'>
                                                            ^- use `this`

js:

function previewLength (input_element, maxLength) {
    var remain = maxLength - input_element.value.length;
    document.getElementById('CounterLength').innerHTML = remain;
}

Upvotes: 1

Related Questions