2013-01-03 106 views
0

我對javascript比較綠,但現在我有一個表單可以通過點擊<button>進行更改,最後他們應該能夠點擊提交按鈕來實際提交併保存表單。onclick觸發提交?

所有其他按鈕都會觸發它們各自的javascript功能,但按下此按鈕時應該更改特定<span id='planname'>標記的innerHTML。

<td><span id=''></span><span id='planname'></span></td> 
<td id='planopt'><button class='button square blue effect-2' onclick="changePlan('Myfixworked','change');">Change</button></td> 

問題是,當我點擊這個按鈕,它運行的功能:

function changePlan(x,action){ 
    if(action == 'change'){ 
     var id = 'planname'; 
     document.getElementById(id).innerHTML = x; 
    } 
} 

它改變該ID的innerHTML但之後,它提交表單。我嘗試重命名該id,併產生相同的結果。我甚至嘗試改變它觸發的函數,併產生相同的結果。如果我更改了id,它將影響此後發生的任何id,例如var id = 'planopt';,它會很好地工作,更改innerHTML並且不會提交表單。

任何幫助,將不勝感激。綜合代碼如下。

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script> 
function changePlan(x,action){ 
    if(action == 'change'){ 
     var id = 'nameofplan'; 
     document.getElementById(id).innerHTML = x; 
    } 
} 
</script> 
</head> 

<body> 
<form action='' method='post' name='quote'> 
    <table border='0' style='border-collapse:collapse;' width='100%' id='serviceplan'> 
     <tr style='border-bottom: 2px solid #3D3D3D;'><th align='left' colspan='2'>Description</th><th align='left' width='30%'>Quantity</th><th width='10%'>Price</th><th align='right' width='25%'>Total</th></tr> 
     <tr style='border-bottom: 1px solid #3D3D3D;'><td class='subt' colspan='5'>Service Plan</td></tr> 
     <tr style='border-bottom: 1px dotted #3D3D3D;'> 
      <td align='left'><span id='nameofplan'>Your Plan</span></td> 
      <td id='planopt'><button class='button square blue effect-2' onclick="changePlan('Your New Plan','change');">Change</button></td> 
      <td>1</td> 
      <td align='center'>$<span id='planprice'>1.00</span>/month</td> 
      <td align='right'>$<span id='subplan'>1.00</span></td> 
     </tr> 
    </table> 
</form> 
</body> 
</html> 

回答

5

將一個type='button'屬性添加到您的按鈕元素。默認情況下,表單元素中的按鈕元素充當提交按鈕。

使用return falsepreventdefault是錯誤的方法,因爲您只是壓制問題的症狀(即您的按鈕是提交按鈕)。

+0

它已經是'button'了。它應該是''那麼。 (我沒有downvote) – Halcyon

+0

@FritsvanCampen也許你不知道按鈕上的'type'屬性。如果一個按鈕的類型沒有被指定爲'button',那麼在某些瀏覽器中它將默認提交它所在的表單。 –

+0

這就是它!該按鈕默認爲提交。測試http://jsbin.com/ijoqaj/1/edit – elclanrs

1

捕獲事件並取消默認操作。

onclick = function (event) { 
    event.preventDefault(); 
} 

您還可以return false;在函數的結束,但如果發生任何錯誤,將取消默認的動作。

+0

這就像製作了一個表格,它的樣式是'display:table- *'。不要壓制提交操作,不要首先使用提交按鈕。 –

+0

你爲什麼這麼說?本地元素的某些默認行爲是可取的。在窗體中有一個'sumbit'按鈕是很方便的,所以按['enter]'鍵可以工作(例如),而您仍然可以通過AJAX將表單提交數據。或者讓鏈接執行一些JavaScript代替,也需要取消點擊的默認操作。 – Halcyon

+0

當然,當你想要一個提交按鈕時,有一個提交按鈕是很方便的。在這種情況下,OP需要相反的* *非提交*按鈕,所以我沒有看到使用提交併修補它的行爲就像非提交按鈕的按鈕。 –