user2650277
user2650277

Reputation: 6739

How to i reset a field value with javascript

I want to make the value in quantity show as 1 if its not valid.

<input type = "number" id = "quantity" value="1" onchange="Validatequantity()" />

function Validatequantity() {   
    var num = document.getElementById('quantity').value;
    if  (num < 1 || num > 10 ) {
        alert('Invalid ticket number ...Should be between 1-10');
        num = 1; // reset part is here(don't work)
    } 
}

Upvotes: 1

Views: 92

Answers (2)

Samurai
Samurai

Reputation: 3729

If you want to work with the variable make it a reference to the element than its value:

function Validatequantity() {   
    var num = document.getElementById('quantity');
    if  (num.value < 1 || num.value > 10 ) {
        num.value = 1;
    } 
}

Upvotes: 1

Tushar
Tushar

Reputation: 87203

function Validatequantity() {
    var num = document.getElementById('quantity').value;
    if  (num < 1 || num > 10 ) {
        alert('Invalid ticket number ...Should be between 1-10');
        num = 1; // reset part is here(don't work)
        document.getElementById('quantity').value = 1; // Set input value to 1
        // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    } 
}

Upvotes: 2

Related Questions