luke121 luke121 - 4 months ago 9
Javascript Question

page is still reloading with event.preventDefault();

if the select drop-down menu has value of NULL, it should stop the page from loading. The jQuery works alerting the user of the issue, however the page still continues to the next page. Any assistance would be superb. Thanks

Luke

<fieldset class="form-group">
<label for="question-1">1. What age group are you?</label> <br>
<select class="drop-down" id = "ageChoice">
<option value="">Please Select</option>
<option value="16minus">16 or below</option>
<option value="16-18">16 to 18</option>
<option value="19-25">19 to 25</option>
<option value="26-34">26 to 34</option>
<option value="35-42">35 to 42</option>
<option value="43-50">43 to 50</option>
<option value="51-60">51 to 60</option>
<option value="61plus">61+</option>
</select>
</fieldset>

<input class="btn btn-primary" type="button" id= "next" value="Next" onClick="location.href='first-test.html' ">

$("#next").click(function () {

var age = $('#ageChoice');

if (age.val() === '') {
event.preventDefault();
alert("Please select your age group, thank you.");

}
else
return;
});

Answer

Ok, so because you have two click handlers, the event is being processed twice. The 'Default' you are trying to prevent is not the onClick="location.href='first-test.html' . That is being processed after your jQuery click function. So we take the onClick out of the html. and add the functionality to the jQuery click event (we could do it either way, but becuase you already have most of the code set up already we'll do it this way)

Here is the reworked code:

<fieldset class="form-group">
  <label for="question-1">1. What age group are you?</label> <br>
   <select class="drop-down" id = "ageChoice">
    <option value="">Please Select</option>
    <option value="16minus">16 or below</option>
    <option value="16-18">16 to 18</option>
    <option value="19-25">19 to 25</option>
    <option value="26-34">26 to 34</option>
    <option value="35-42">35 to 42</option>
    <option value="43-50">43 to 50</option>
    <option value="51-60">51 to 60</option>
    <option value="61plus">61+</option>
  </select>  
</fieldset>

  <input class="btn btn-primary" type="button" id= "next" value="Next">

and the jquery:

$("#next").on('click', function (event) {

    var age = $('#ageChoice');

    if (age.val() === '') {
      alert("Please select your age group, thank you.");
    } else {
      location.href='first-test.html'
    }
});