newbie2015
newbie2015

Reputation: 251

Delete character on button click unless the input value is 0

Presently I am using the following code to delete a character from an input display:

function deleteChar(input) {
  input.value = input.value.substring(0, input.value.length - 1)
}

Unfortunately, if the display reads just one character, this function when activated on button click will leave the input display blank. I would like for it to return 0 in such circumstances. I have tried targeting the string length, but I have not been successful. How can I amend this function to achieve the desired effect?

Upvotes: 1

Views: 486

Answers (4)

Nelson
Nelson

Reputation: 2177

I propose another ternary version

function deleteChar(input) {
  nV = input.value.substring(0, input.value.length - 1);
  input.value = nV ? nV : 0;
}

Code explanation:

  1. assign the new value to the variable nV

  2. assigns the input.value based on the ternary operator

This assignment is equivalent to the following:

if (nV) {
  input.value = nV;
} else {
  input.value = 0;
}

Upvotes: 1

MortenMoulder
MortenMoulder

Reputation: 6648

function deleteChar(input) {
    if(input.value.length == 1) {
        input.value = 0;
    } else {
        input.value = input.value.substring(0, input.value.length - 1);
    }
}
<input type="text" value="123" id="inputElement" />
<button onclick="deleteChar(document.getElementById('inputElement'))">Click</button>

If you want a shorter version, feel free to use this (which includes a ternary operator):

function deleteChar(input) {
    input.value = input.value.length == 1 ? 0 : input.value.substring(0, input.value.length - 1);
}

Upvotes: 3

Paul
Paul

Reputation: 141839

I would use the ternary operator for this:

function deleteChar(input) {
    input.value = input.value.length === 1 
      ? 0 
      : input.value.substr( 0, input.value.length - 1 )
    ;
}

Upvotes: 1

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Are you looking for something like this:

function deleteChar(input) {
    if(input.value.length == 1) return 0;         //return 0 if there is only 1 character
    input.value = input.value.slice(0, -1);
}

Upvotes: 1

Related Questions