簡體   English   中英

按下ENTER鍵時,強制表單通過(如果有多個)發​​送某些提交按鈕

[英]Force form to send certain submit button through (when there are multiple) when ENTER key pressed

我有一個帶有兩個提交按鈕的表單,分別為name="submit_button"name="search_me_logo" ,當表單到達action位置時,它會根據按下的按鈕執行兩項不同的操作。

當按下回車鍵時,我希望它執行與name="submit_button"相同的操作,但是現在它似乎默認情況下正在發送name="search_me_logo"

這是您需要的HTML代碼:

<form action="/search_me.php" method="GET">
    <div id="search_me_outer_div">
        <button id="search_me_div" name="search_me_logo" type="submit">
            <img id="search_me_image" src="/images/header/search_icons/search_me.png" height="33" alt='"search me"'/>
        </button>
    </div><!--
    --><div id="search_box_outer_div">
        <div id="search_box_div">
            <input id="search_box" onfocus="hidePlaceholderAndShineBox();" onblur="showPlaceholderAndBlurBox();" name="search" type="text" spellcheck="false" size="32" placeholder='Get to know Sam... "search me"'>
            <button id="search_div" name="submit_button" type="submit">
                <img id="search_img" src="images/header/search_icons/fancy_search.png" height="21" alt="Go"/>
            </button>
        </div>
    </div>
</form>

PHP:

if (isset($_GET['submit_button'])) {
    echo 'submit was pressed<br>';
} else if (isset($_GET['search_me_logo'])) {
    echo 'logo was pressed<br>';
} else if (isset($_GET['search'])) {
echo 'enter was pressed<br>';
} else {
    //show error page
}

現在,當我按下Enter鍵時,它echo s“按下了徽標”。 JavaScript可能有一種方法,但是如果僅使用HTML / PHP就可以,那就太好了。

默認情況下,按Enter鍵將導致第一個提交按鈕。 您可以直接在表單開頭的隱藏div中添加默認的Submit操作。 例如:

<form action="/search_me.php" method="GET">
<div style="height:0px; width:0px; overflow:hidden;"><button id="search_div" name="submit_button" type="submit"></button></div>

其余的保持原樣。

編輯:如果沒有顯示第一個按鈕,某些瀏覽器將不允許Enter鍵觸發它(例如display:none;)。

但是它將與:

width: 0;
height: 0;
overflow: hidden;

在包含隱藏的提交按鈕的元素的CSS中。

感謝所有的建議。 @NoGray的答案可能有效,或者我只是按照@Irdrah的建議做了兩種形式。

每個表單的按鈕和輸入具有不同的名稱,其中一個輸入具有type="hidden"id="hidden_input" 然后,當單擊帶有隱藏輸入的表單的提交時,我使用了jQuery的submit()進行設置

document.getElementById('hidden_input').value = document.getElementById('shown_input').value;`

return ed true 我沒有嘗試過@NoGray,但我敢肯定它會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM