Vue Js input events are firing at the same time

135 views Asked by At

So I have the following form:

<FormulateForm @submit="onSubmit">
 <FormulateInput
        type="text"
        label="Total Time"
        name="totalTime"
        validation="^required"
        @keydown="isNumber"
        v-on:blur="formatDigits($event,'totalTime')"
      />

      <FormulateInput
        type="text"
        name="restingDuration"
        label="Resting Duration"
        validation="^required"
        @keydown="isNumber"
        v-on:blur="formatDigits($event, 'restingDuration')"
      />
</FormulateForm>

the format digits function just formats the number input like 212 -> 2:12. The blur event is working fine however keydown and blur event is happening on every input field and it undoes the previous input field's formatting when I modify the second one. Is there a way to bind the event and blur event to a specific field instead of it firing on every keypress?

Here's the format function:

   formatDigits(event, name) {
      const inputVal = event.target.value;
      let final;

      if (event.target.name === name) {
        if (inputVal?.length > 0 && inputVal?.length <= 2) {
          let minutes = this.clamp(inputVal.slice(0), 0, 59);

          final = '0000:' + minutes;

        } else if (inputVal?.length > 2 && inputVal?.length <= 6) {
          const secondsIndex = inputVal.length - 2;

          const hours = this.clamp(
            inputVal.slice(0, secondsIndex),
            0,
            9999,
            true,
            4,
          );

          const minutes = this.clamp(
            inputVal.slice(secondsIndex, inputVal.length),
            0,
            59,
          );

          final = hours + ':' + minutes;
        } else {
          //invalid length
          return;
        }
        event.target.value = final;
      }
    },

Here's the clamp function:

clamp(val, min, max, isHours, lengthMax) {
  const ret = val > max ? max : val < min ? min : val;

  if (isHours) {
    if (ret.length < lengthMax) {
      const zeroes = '0'.repeat(lengthMax - ret.length) + ret;
      return zeroes;
    }

    return ret;
  }

  return ret.toString().length % 2 === 0 ? ret : '0' + ret;
},
0

There are 0 answers