提交时无需刷新

时间:2014-05-20 17:38:54

标签: html forms submit refresh onsubmit

我有一个带有表单的网站。

输入值应为特定值。这有效:

$('button').on('click', function () {
    var val1 = $("#teller").val();
    var val2 = $("#noemer").val();
    if (val1 == 3 && val2 == 10)
        alert("Goed gedaan! je hebt de vraag goed beantwoord. Je kunt verder met je avontuur!");
    else
        alert("Helaas... Dit is niet het goede antwoord. Probeer het nog eens!");
});

但是当我提交页面时会刷新,更改我的网址并刷新页面,以便页面再次从头开始...这是网站:http://stilld.nl/brrreuk/

我不希望这种情况发生。我希望代码检查给定的值是否正确,但我希望网站保持原样。

希望你能提供帮助。

这是html:

<form id="form_1">
    <fieldset>
        <p>
            <input type="text" class="input_required" id="teller" name="teller" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
            <label for="teller"></label>
        </p>
        <hr noshade size=3>
        <p>
            <input type="text" class="input_required" id="noemer" name="noemer" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">
            <label for="noemer"></label>
        </p>
        <p>
            <button class="submit" type="submit" value="controleer">Controleer</button>
        </p>
    </fieldset>
</form>

2 个答案:

答案 0 :(得分:2)

你走了。只需将submit更改为button

JavaScript:

$('button').on('click', function(){
    var val1 = $("#teller").val();
    var val2 = $("#noemer").val();
    if(val1 == 3 && val2 == 10)
        alert("Goed gedaan! je hebt de vraag goed beantwoord. Je kunt verder met je avontuur!");
    else
        alert("Helaas... Dit is niet het goede antwoord. Probeer het nog eens!");
});

和HTML

<p>
    <input type="text" class="input_required" id="teller" name="teller" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">       
    <label for="teller"> </label>
</p>
        <hr noshade size=3>
<p>
    <input type="text" class="input_required" id="noemer" name="noemer" maxlength="2" class="valid" aria-invalid="false" onkeydown="return isNumber(event);" placeholder="?" onfocus="this.placeholder = ''" onblur="this.placeholder = '?'">       
    <label for="noemer"> </label>
</p>
<p>
    <button type="button" value="controleer"> Controleer </button>
</p>

答案 1 :(得分:0)

列出表单的submit事件而不是按钮的click事件:

$('form').on('submit', function(e) {
    e.preventDefault();

    // do stuff
    // $(this).trigger('submit') if everything's ok
});
  

注意: e.preventDefault();行很重要!