以“搜索”按钮为目标的OnPress事件会触发整个页面的“提交”按钮


OnPress Event targeting a Search button triggers Submit button for entire page

作为注册过程的一部分,我有以下表格:

<form class="form1" id="register_form1" method="POST" action="<?php echo $register_url; ?>" name="register_form1">
<!-- other parts of the form that are not relevant to this question -->             
<!-- text input area to conduct a search -->
 <span style="text-align: left; width: 100%;margin-left:40px;">Select a primary recruiter</span>
 <div class="ansDiv">
 <table style="float: left;">
   <tr>
   <td>
   <input type="text" id="primary_recruiter" name="primary_recruiter" value="" onkeypress="searchKeyPress(event);"> 
   </td>
   <td>
   <input type="button" id="buttonSearch" value="" class="button_search" name="seachprimary" onclick="javascript: searchRecruiter();">
   </td>
   <td>
   <a class="highlight" href="../images/PrimaryRecruiter.gif" style="float: right; padding-right: 655px;">
   <img src="../images/Q-btn.png">
   </a></td>                    
   <td>
   <input type="hidden" id="primary_recruiter_id" name="primary_recruiter_id" value="">
   </td></tr>
</table>            
<!-- last part of the form that is not relevant to this question -->
<!-- Submit button for the page itself. -->
<p align="center">
  <input type="submit" class="button_submit" name="register1_submit" value="" />
</p>
</form>

这是我设置的JavaScript,用于在Enter上实现按钮按下:

<script type="text/javascript">
 function searchRecruiter(){
 var temp = $("#primary_recruiter").val();
    $.ajax({
        type : 'GET',
        url : 'searchrecruiter.php',
        data: "name="+temp,
        success : function(data){
         $("#displayrecruiterlist").html(data);
        }//end function(data) call
  });//end $.ajax call
 }//end searchRecruiter
//other java scripts
</script>

<!-- Press enter to search... -->    
  <script type="text/javascript">
    function searchKeyPress(e){
        // look for window.event in case event isn't passed in
        if (typeof e == 'undefined' && window.event) { e = window.event; }
        if (e.keyCode == 13){
            document.getElementById('buttonSearch').click();
        }               
    }
</script>
            

当我在文本输入框上按enter键时,我确实会进入document.getElementByID('buttonSearch').click();,这样就可以了。但后来页面的响应就像我点击了提交一样,提交并没有id属性。

当我点击搜索按钮时,它会按预期工作。我做错了什么?我以为我是在点击"搜索"按钮,但这不是我的反应。

需要记住的是:我是网络开发(PHP、JavaScript等)的新手,正在工作中学习。如果我需要其他需要提供的东西,请告诉我。

在文本输入字段上按enter键将提交父窗体。因为搜索字段/按钮实际上是在执行自己的功能(通过AJAX调用提取数据),所以它们可能根本不应该在窗体内部。我建议将这些项目取出并放在表单标签之外。这会解决你的问题。

另一种选择是在onkeypress事件中返回false。

仅供参考,onclick="是javascript语法,因此开头的javascript:是隐含的,没有必要。