我有一个表单,有两个提交按钮,name="submit_button"
和name="search_me_logo"
,当表单到达action
位置时,它会根据按下的按钮做两件不同的事情。
当按enter键时,我希望它做与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
}
现在当我按回车键时,它是echo
' s "logo被按下了"。使用JavaScript可能有办法,但如果可以只使用HTML/PHP,那就太好了。
默认情况下,按回车键会出现第一个提交按钮。您可以简单地在表单开头的隐藏div中添加默认提交操作。例如:
<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>
,其余的保持原样。
编辑:有些浏览器不允许输入键触发第一个按钮,如果它没有显示(例如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
和true
。我没有试过@NoGray's,但我相信它会起作用的。