Search code examples
javascripthtmldisabled-input

disable submit input in html


When I tried this code the button input stays disabled even if there is a value in the input, why?

<form action ="/buy" method = "POST">
    <input id="symbol" type='text' name= 'symbol'/>
    <input id="shares" type= 'text' name = 'shares'/>
    <input id="submit" type= 'submit' disabled/>
</form>
<script>
    document.querySelector('#shares').onkeyup = function(){
        if (document.querySelector('#shares').value === '') {
            document.querSelector('#submit').disabled = true;
        } else {
           document.querSelector('#submit').disabled = false;  
        }
    }
</script>

Solution

  • Everything is right apart from this statement in else, you have an error with syntax

    <form action ="/buy" method = "POST">
        <input id="symbol" type='text' name= 'symbol'/>
        <input id="shares" type= 'text' name = 'shares'/>
        <input id="submit" type= 'submit' disabled/>
    </form>
    <script>
        document.querySelector('#shares').onkeyup = function(){
            if (document.querySelector('#shares').value === '') {
                document.querySelector('#submit').disabled = true;
            } else {
               document.querySelector('#submit').disabled = false;  
            }
        }
    </script>
    

    Working fiddle: https://jsfiddle.net/akcvtf2r/