Question

I want to automatically run a function upon loading the webpage, and then I want to give the option to rerun the function after it's executed.

The following code will work if I the part is not in the database, and will work if instead of using document.write is use alert for displaying the part, but if I use document.write, the button to search again disappears. I think it's because the buttons aren't being re-initialized. I've moved that around and gotten nothing, and tried reloading the webpage, which is functional, but unsatisfactory because of the time it takes.

Is there anyway to prevent the buttons from disappearing, or a better method you recommend?

Thanks in advance.

<!DOCTYPE HTML>

<html>

<body>
        <input id="clickMe" type="button" value="Search for Another Part" onclick="search_part();" />
        <script type="text/javascript">

            function search_part()
            {                                   
                    var part = prompt("Stackoverflow example: ");

                    if( typeof part === 'undefined' )
                    {
                            alert("That part is not in the database.")
                    }
                    else 
                    {
                            document.write( part )
                    }
            }
            window.onload = search_part();

            document.getElementById("Button").onclick = search_part;

    </script>

Was it helpful?

Solution

After DOM is loaded, document.write replaces all content on page. Instead you probably want to have a element container on body and display messages in that.

<input id="clickMe" type="button" value="Search for Another Part">

<div id="messages-here"></div>

<script type="text/javascript">

    function search_part () {
        var part = prompt("Stackoverflow example: ");

        if (typeof part === 'undefined') {
            alert("That part is not in the database.");
        } else {
            document.getElementById('messages-here').innerHTML = part;
        }
    }

    window.onload = search_part();

    document.getElementById("clickMe").onclick = search_part;

</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top