Search code examples
javascripthtmlbordertextinput

Javascript to show/hide text input border


Sorry for the really basic/simple question, I'm very new to front end web development.

I've looked at lots of the questions about using Javascript to show/hide things on a web page but none of them talk about specifically showing/hiding a text input border.

On my page I have a text input and a button.

When the page loads I don't want the text input border to be visible.

When the button is clicked I want it to change the state of the text input border (IE: if the text input border is not showing when the button is clicked then it calls a javascript function to make the text input border visible. If the text input border is visible then the javascript function the button calls would make the text input border invisible.)

Here is my code so far:

<html>
    <head>
        <title>Text Input Border test</title>
    </head>
    <body>
        <br>
        <input type="text" id="address1" value="test text input" class="question-text" size=30> 
        <br>
        <input type="button" value="Click me" onclick="showBorder()">
    </body>
    <script type="text/javascript">
        function showBorder () {
            var myInput = document.getElementById("address1").style;
            myInput.borderStyle="solid";
        }
    </script>
    <style scoped lang="scss">
        .question-text {
            border: 0;
        }
    </style>
</html>

When the button is clicked there are no visible changes to the text input border or the page in general for that matter.

Any direction would be much appreciated, I'll be sure to upvote any help and mark the most applicable answer as accepted. Thanks in advance.


Solution

  • try this:

    <html>
        <head>
            <title>Text Input Border test</title>
        </head>
        <body>
            <br>
            <input type="text" id="address1" value="test text input" class="question-text" size=30> 
            <br>
            <input type="button" value="Click me" onclick="toggleBorder()">
        </body>
        <script type="text/javascript">
            function toggleBorder () {
                var myInput = document.getElementById("address1");
                myInput.classList.toggle('question-text-border');
            }
        </script>
        <style scoped lang="scss">
            .question-text {
                border: 0;
            }
            .question-text-border {
                border: 1px solid black;
            }
        </style>
    </html>
    
    • classList is basically an array with a few special functions: Class List Docs
    • calling toggle on class list removes the class if present and adds it if absent
    • The bottom css class .question-text-border overrides the class .question-text

    Let me know if there is anything I need to clarify.