The reason why qty = ''
isn't working is that you've assigned the string value of the input to that variable. Setting it to an empty string won't make the value of the input change - you need to explicitly change the element's value.
So, a few things first:
- It's often useful to cache your elements first.
- Remove the inline JS and replace it with
addEventListener
and attach it to the button element (a more modern approach).
- Use a
<button>
element instead of an <input type="button">
- Assign the total to an element's text content/innerText instead of
document.write
for various reasons.
Then when the handler is called coerce the string value of the input to a number, and use that in the condition. If the number is less than zero assign an empty string to the input value.
// Cache the elements
const qty = document.querySelector('#qty');
const result = document.querySelector('#result');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', add);
function add() {
// Coerce the input value to a number
const val = Number(qty.value);
if (val > 0) {
// Instead of `document.write` assign
// the total to the text content of an element
result.textContent = val * 25;
} else {
// Set the value of the qty element to
// an empty string
qty.value = '';
console.log('no');
}
}
#result { margin-top: 0.5em; }
<input type="number" id="qty">
<button type="button">Add</button>
<div id="result"></div>