raffayatiq
raffayatiq

Reputation: 159

Javascript code does not execute?

I'm working on a project. I'm trying to make my code so that when a user submits an option from a dropdown menu, if the user selects and submits the default ("Select a genre"), the form is not submitted and the page is not refreshed. Following is my Javascript code:

<script>

    var menu = document.getElementById("submit");
        menu.addEventListener("click", function() {
            if (document.getElementById("dropdown").value == 'nothing')
            {
                return false;
            }
        });

</script

This is nested inside a head tag.

Following is my HTML code for the form:

<div>
    <form method="POST">
        <select id="dropdown" name="genre">
            <option value="nothing">Select a genre</option>
            <option value="rock">Rock</option>
        </select>
        <br/>
        <br/>
        <input id="submit" type="submit"/>
     </form>
</div>

The javascript doesn't seem to work, since even when I submit the form while selecting the "Select a genre" option, my form is still submitted, and the python code does work on the value 'nothing', which gives errors.

EDIT: Upon adding further functionality to my project by adding more javascript code, the javascript code again didn't work. I used google chrome's developer tools and stumbled upon this error which seems to be related to why the code isn't working:

Uncaught TypeError: $(...).addEventListener is not a function
    at (index):18

Upvotes: 0

Views: 1904

Answers (2)

Sam Ho
Sam Ho

Reputation: 206

It is just a declaration of Code if you don't bind to $( document ).ready() or make it as self-invoking function.

First solution:



    $( document ).ready(functino(){
        var menu = document.getElementById("submit");
            menu.addEventListener("click", function() {
                if (document.getElementById("dropdown").value == 'nothing')
                {
                    return false;
                }
            });
    });


Another Solution:

(function(){
var menu = document.getElementById("submit");
        menu.addEventListener("click", function() {
            if (document.getElementById("dropdown").value == 'nothing')
            {
                return false;
            }
        });
}());

Upvotes: 0

Mamun
Mamun

Reputation: 68933

Try event.preventDefault():

var menu = document.getElementById("submit");
menu.addEventListener("click", function(event) {
  if (document.getElementById("dropdown").value == 'nothing')
  {
      event.preventDefault();
  }
});
<div>
    <form method="POST">
        <select id="dropdown" name="genre">
            <option value="nothing">Select a genre</option>
            <option value="rock">Rock</option>
        </select>
        <br/>
        <br/>
        <input id="submit" type="submit"/>
     </form>
</div>

Upvotes: 1

Related Questions