表單提交(submit)時使用preventDefault可能產生的問題


作者: | 2011/04/12 14:58:28 | 5 則迴響



在表單內的任一輸入框按下Enter後,預設情況下表單會自動提交,若使用preventDefault阻止後,表單將從此不能Submit,怎麼辦?

一般我們設計HTML表單後,若在Form內的文字框按下Enter,預設會觸發Submit事件,造成表單提交。但若有某些文字框我們有特別的用途,希望它按下Enter後不要Submit表單,而是去做一些特定的動作,此時我們可以先使用preventDefault,之後再讓表單可以被Submit嗎?

舉例來說,假設我們設計了一個表單,裡面有一個可輸入「代號」的文字框,以及一個會出現該代號對應的「名稱」文字框。

這時需求要的情境是,輸入代號後,按下Enter,名稱文字框就會立即出現該代號對應的名稱,經過使用者判斷確認這是他要選的代號及名稱,才按下submit鍵送出結果。

我們先做form的設計,如下:


<form id="new" action="" method="POST">
    <input type="text" id="code" name="code"> <!-- 代號輸入框 -->
    <input type="text" id="name" name="name"> <!-- 名稱出現框 -->
    <input type="submit" id="submit" value="提交" />
</form>

好的,接著我們用jQuery來撰寫「在代號框輸入數值後會自動出現對應名稱」的程式碼:

$(function(){
    // 偵測若在代號框輸入值後,按下Enter,就填進對應的名稱 
    $('#code').keydown(function(e){
        // Enter鍵值為13
        if (e.keyCode == '13') {
            // 觸發填值的動作,在此省略
        }
    });
});

此時問題就會發生了,因為在還沒執行到填值時,我們的Enter動作早已先觸發了submit鍵的click動作,對應名稱都還沒出現,表單就被提交了。
這時也許你會想到要使用preventDefault()去阻擋預設的提交動作:


$(function(){
    // 偵測若在代號框輸入值後,按下Enter,就填進對應的名稱
    $('#code').keydown(function(e){
        // Enter鍵值為13
        if (e.keyCode == '13') {
            // 觸發填值的動作,可能用get或load等ajax取值...
        }
    });

    // 表單的submit都會進來這兒
    $('#submit').click(function(e){
        e.preventDefault(); // 成功阻擋Enter的submit動作!
    });
});


是的,成功阻擋了submit,但是若您手動去按提交鍵會發現submit動作也被擋了,再也提交不出表單了XD。於是有人會問,如何在使用過e.preventDefault後,再一次讓submit復活呢(reenable submit)!?? 唉,我也沒試出來XD,不過在此可以使用一個workaround的方式解決。

重新解讀我們想完成的事情就是–希望submit事件不要在代號框取得focus時會return true,讓它好好的做它該做的事:去把名稱填好。了解這樣的方式後,解決方式幾乎就呼之欲出了:


$(function(){
    // 用來判斷是否submit的flag
    var fSubmit = false;

    // 偵測若在代號框輸入值後,按下Enter,就填進對應的名稱
    $('#code').keydown(function(e){
        // Enter鍵值為13
        if (e.keyCode == '13') {
            // 觸發填值的動作,可能用get或load等ajax取值
        }
    }).focus(function(){ // 代號框取得focus,這時擋下所有的submit事件
        fSubmit = false;
    }).blur(function(){
        fSubmit = true; //代號框失去focus,這時允許submit
    })

    // 表單的submit都會進來這兒
    $('form').submit(function(e){
        return fSubmit; // 傳回true就會submit,傳回false就表示不作submit
    });
});


如此就可以滿足一開始所提的需求。
至於如何在使用過preventDefault後再次submit呢?期待各位先進可以分享,感謝!


標籤:,

分類:,

本文作者是Audi Lu

5 則留言

  • sheephead says:

    你好喔
    ㄏ 你們的文章寫得很讚
    不過就這個範例而言應該不用那麼麻煩

    只要在按下ENTER裡面的判斷最後加上e.preventDefault();就可以了
    不用特意去處理submit那一段程式碼。

  • alton says:

    Welcome to my blog ,
    I’m Alton.
    If you’ve ever been too tired and couldn’t finish a research paper , then you’ve come to the right place. I help students in all areas of the writing process . I can also write the paper from start to finish.
    My career as a professional writer started during my school years . After learning that I was very skilled in the field of academic writing, I decided to take it up as a profession.

    Skilled Academic Writer- Alton Sawyer- 10 Most Common College Freshman Mistakes Confederation

  • kalem says:

    Hello, I’m Kalem.
    Welcome to my homepage . I started writing in high school after a creative writing assignment for my English teacher. I did creative writing for almost a year before I thought about doing something else.
    I had always loved doing research assignments because I’m passionate about learning. When you combine writing ability with a love of learning, dissertation writing only makes sense as a job.
    I’m passionate about helping the students of the future in their school career. When they don’t have time for their paper , I am there to help.

    Kalem Warner – Professional Academic Writer – Writing recources hints Company

  • montell says:

    Hello, it’s Montell here!
    I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing skills in college. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my first semester of college.
    Ever since high school, I have continued to work as a professional writer. I was hired by a writing company based in the United Kingdom. Since then, the dissertations that I have written have been sold around Europe and the United States.
    In my line of work, I have become accustomed to hearing, “Montell, can you help me meet my writing assignment deadline?” I know that I can save their time.

    Academic Writer – Montell Rivera – Seven tips for writers Corp

  • ianis says:

    Hello guys, my name is Ianis!

    I`m an academic writer and I`m going to change your lifes onсe and for all
    Writing has been my passion for a long time and now I can`t imagine my life without it.
    Most of my works were sold throughout Canada, USA, China and even India. Also I`m working with services that help people to save their nerves.
    People ask me “Please, Ianis, I need your professional help” and I always accept the request, `cause I know, that only I can solve all their problems!

    Academic Writer – Ianis Bowers – 7stepdesign.com Team

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。

*

*

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料