`
<input type="number" id="qty">
<input type="button" onclick="add()" value="Add">
<script>
function add(){
qty = document.getElementById('qty').value
if(qty>0){
var tot = qty*25
document.write(tot)
}else{
qty = ""
alert("no")
}
}
</script>
'qty=""' is the correct way as mentioned on google. but not working for me.
CodePudding user response:
Try
document.getElementById("qty").value = "";
and cast qty to number in your if
if(Number(qty) > 0)
CodePudding user response:
Values of inputs are always string
, try this one in your condition :
if(Number(qty)>0){
...
}
CodePudding user response:
Use this below code to clear the input
qty.value = "";
CodePudding user response:
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>
CodePudding user response:
if you want to check in time when you enter a value (as I understood from the question), you must have a listener on <input type=" number" id="qty">
and event
'input'. qty.addEventListener('input', (e)=>{ // .... make your validation })