2010-09-19 73 views
6

我已經構建了一個相當複雜的表單,其中包含一個隱藏區域,用戶可以根據需要切換打開以輸入更多信息。然而,當你點擊標記爲的這個切換按鈕時,我有更多的原生,它觸發提交按鈕並提前提交表單。爲什麼jQuery「切換」按鈕觸發表單上的提交按鈕?

窗體現在在開發中,但它可以被發現here

我使用的切換按鈕的代碼爲:

<script type="text/javascript"> 
    $(function() { 
     $("#schedule").accordion({ header: "h5", collapsible: true }); 
     $("#more-nativities").hide(); 
     $("#toggle").click(function() { 
      $("#more-nativities").slideToggle("slow"); 
     }); 
    }); 
    </script> 

提交按鈕的代碼非常簡單:

<input id="submit2" type="image" src="_images/btn_register.jpg" name="submit" alt="" onmouseover="javascript:this.src='_images/btn_register2.jpg'" onmouseout="javascript:this.src='_images/btn_register.jpg'"/> 

的切換按鈕的代碼爲:

<button id="toggle">I have more nativities</button> 

關於爲什麼切換按鈕觸發提交的任何想法?更重要的是如何解決這個問題?

謝謝!

+4

另外,我建議不要使用[inline JS。寫不顯眼的Javascript](http://stackoverflow.com/questions/1064166/is-there-any-good-reason-for-javascript-to-be-inline)。 – 2010-09-19 22:34:00

+0

提供儘可能多的相關代碼是非常有用的。我在原始代碼中編輯切換按鈕。 – 2010-09-19 22:46:44

回答

11

嘗試增加一個類型,即:

<button type="button" id="#toggle">Text</button> 

http://www.w3schools.com/tags/tag_button.asp說,這應該總是被定義。瀏覽器可能默認爲提交按鈕。

+0

我不知道你看到了什麼,但按鈕沒有類型。 – 2010-09-19 22:37:59

+0

在我的瀏覽器上看不到它。我所有的是: n00dle 2010-09-19 22:38:03

+0

@SimpleCoder - 我沒有意識到這是代碼被引用...我認爲這是關於''按鈕。 OP中不包含'

1

嘗試

return false; 

上點擊功能來回切換按鈕滑動切換後。

1

從W3Schools的:

始終指定 按鈕類型屬性。 Internet Explorer的默認類型是「按鈕」,而其他瀏覽器中的 (以及W3C 規範中)則是「提交」。

http://www.w3schools.com/tags/tag_button.asp

一定要指定type="button"

2

埃斯特班有一個解決方案。在jQuery tutorial中描述了更好的一個:

$(document).ready(function(){ 
    $("a").click(function(event){ 
    alert("As you can see, the link no longer took you to jquery.com"); 
    event.preventDefault(); 
    }); 
});