Can't console.log("xyz") after clicking a button.

It seems the javascript function is never executed. Can anyone tell me why?

<form>
    <select type="text" name="month" id="month">
        <option value="01">January</option>
        <option value="02">February</option>
        <option value="03">March</option>
        <option value="04">April</option>
        <option value="05">May</option>
        <option value="06">June</option>
        <option value="07">July</option>
        <option value="08">August</option>
        <option value="09">September</option>
        <option value="10">October</option>
        <option value="11">November</option>
        <option value="12">December</option>
    </select>
    <button type="submit" id="jobmonth">View all job requests in this month</button>
    </form>

    <script type="text/javascript">
         $('#jobmonth').click(function() {
              console.log("work");
              var month = $('#month').val();
              console.log(month);
    }
    </script>

None of the console.log work. PS- Sorry for such a silly question. I'm just a beginner in JS.

2 answers

  • answered 2017-06-17 19:11 Bert Evans

    Buttons of type submit are intended to submit the form to whatever it's action is. In this case, it would just refresh the page.

    Instead, just change the type to button.

    <button type="button" id="jobmonth">View all job requests in this month</button>
    

    This will not submit the page and you will see your logged results.

  • answered 2017-06-17 19:11 Maxime G

    Try giving an ID to your tag, then using the submit event instead. This means the console.log will be triggered when the form is submitted rather than the button being clicked, but the result should be the same:

    <form id="myform">
        <select type="text" name="month" id="month">
            <option value="01">January</option>
            <option value="02">February</option>
            <option value="03">March</option>
            <option value="04">April</option>
            <option value="05">May</option>
            <option value="06">June</option>
            <option value="07">July</option>
            <option value="08">August</option>
            <option value="09">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>
        <button type="submit" id="jobmonth">View all job requests in this month</button>
        </form>
    
        <script type="text/javascript">
             $('#myform').on('submit', function() {
                  console.log("work");
                  var month = $('#month').val();
                  console.log(month);
        }
        </script>
    

    You can also use the "submit" shorthand: https://api.jquery.com/submit/