Home > Net >  JavaScript: How can i give the value of 0 to an html element everytyme it is not focused
JavaScript: How can i give the value of 0 to an html element everytyme it is not focused

Time:09-02

I'm trying to assign the value 0 to an input in my html, so every time is not focused the input value inside is set to 0 so I don't get the empty input, but it doesn't work.

HTML5 code:

<div >
    <button  onclick="decrement('1')">-</button>
    <input type="number" id="1" value="0" name="quantidade" min="0" max="100"  onfocusout="reset_quantity(1)">
    <button  onclick="increment('1')"> </button>
</div>

JavaScript code:

function reset_quantity(id) {
    var input = parseInt(document.getElementById(id)).value;

    console.log(typeof input);
    if (input == undefined) {
        input.value = 0;
    }
}

CodePudding user response:

function reset_quantity(id) {
    var input = parseInt(document.getElementById(id).value);
    value = isNaN(input) ? 0 : input;
    console.log(typeof input);


    if (value == "") {
        document.getElementById(id).value = 0;
    }

    if (value > 100) {
        document.getElementById(id).value = 100;
    }
}

CodePudding user response:

const ingredientCounters = document.querySelectorAll('.ingredient-counter')

ingredientCounters.forEach(el => {
  el.addEventListener('blur', () => {
    el.value = 0
  })
})
<div >
  <button  onclick="decrement('1')">-</button>
  <input type="number" id="1" value="0" name="quantidade" min="0" max="100" >
  <button  onclick="increment('1')"> </button>
</div>

  • Related