1

I am trying to listen for submit event of form.I have included my js files finely and also written my form element correctly.It keeps on screming

Uncaught TypeError: Cannot read property 'addEventListener' of null

My HTML File

/*Form Listener*/
var form = document.getElementById('myForm');
form.addEventListener('submit', saveBookmark);

function saveBookmark(e){
	e.preventDefault();
	console.log('Form Submitted');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <title>Bookmark App | Home</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
</head>
<body>
    <div class="container">
        <header>
            <h2 class="text-center">Bookmark App</h2>
            <hr>
        </header>
        <section>
            <div class="jumbotron">
                <div class="text-center">
                    <h3>Bookmark Your Favorite Sites</h3> <br>
                    <form id="myForm">
                        <div class="form-group">
                            <label>Website Name</label>
                            <input type="text" class="form-control" placeholder="Enter Website Name" id="siteName">
                        </div>
                        <div class="form-group">
                            <label>Website URL</label>
                            <input type="text" class="form-control" placeholder="Enter Website URL" id="siteUrl">
                        </div>
                        <button class="btn btn-lg btn-primary" type="submit">
                            Submit
                        </button>
                    </form>
                </div>
            </div>
        </section>
    </div>
</body>
</html>

My JS file

Any help would be appretiated

2
  • 3
    make this line of code to be very last element of your body tag <script type="text/javascript" src="js/main.js"></script> Commented Jan 12, 2017 at 6:53
  • because you are trying to access your element, where it isn't loaded yet Commented Jan 12, 2017 at 6:54

1 Answer 1

3

HTML (and JavaScript) run from top to bottom.

Assuming that the JavaScript that you have loaded is in main.js then this is loaded and processed before the html containing the element myForm has loaded.

Instead, you need to move your reference to main.js to the bottom of your html (somewhere below the </form> closing tag).

Sign up to request clarification or add additional context in comments.

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.