1

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)
    } 
}

2 Answers 2

2
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
        // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    } 
}
Sign up to request clarification or add additional context in comments.

4 Comments

isn't it same as num=1 because num = document.getElementById('quantity').value
It is not live node, I think
You can give me a link to an article talking about it so that i can learn ...it works btw
@user2650277 stackoverflow.com/a/19145320/2025923 the element is live but not the value
1

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;
    } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.