页面仍在使用event.preventDefault()重新加载;

时间:2016-07-24 21:46:15

标签: javascript jquery

如果选择下拉菜单的值为NULL,则应该停止加载页面。 jQuery可以警告用户该问题,但页面仍然继续到下一页。任何援助都是一流的。谢谢

卢克

<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;
});

1 个答案:

答案 0 :(得分:1)

好的,因为你有两个点击处理程序,事件正在被处理两次。你试图阻止的'默认'不是onClick =“location.href ='first-test.html'。这是在你的jQuery点击功能之后处理的。所以我们从html中取出onClick。并添加jQuery click事件的功能(我们可以这样做,但是因为你已经设置了大部分代码,我们就这样做了)

以下是重写代码:

<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">

和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'
    }
});