2014-02-25 34 views
0

我正在嘗試使用jQuery UI構建一個對話框,並且是/否按鈕以供用戶確認。 (這是因爲我想使用戶界面統一,因爲我使用jQuery UI來構建警告對話框。)我的意圖是要求用戶確認是否在文本框中提交了大量(1000或更高)。到目前爲止,我的JavaScript代碼如下所示:我們如何檢查在jQuery UI對話框中單擊了哪個按鈕?

function checkclick(button1, button2, theForm) { 
    var val; 
    val = theForm.mybox.value; 
    v = parseInt(val) || 0; 
    var btns = {}; 
    btns[button1] = function(){ 
     $(this).dialog('close'); 
    }; 
    btns[button2] = function(){ 
     $(this).dialog('close'); 
    }; 

    if (v >= 1000) { 
     $('#dialog').dialog({ 
     autoOpen: true, 
     modal:true, 
     buttons:btns 
     }); 
     $('#dialog_link').click(function() { 
      $('#dialog').dialog('open'); 
     }); 
     return false; 
    } 
    return true; 
} 

我的HTML看起來像這樣:

<div id='dialog' title='Note' style='display:none'> 
<p id='dialog_link'>This is a very large number. Are you sure?</p> 
</div> 

<form name='myForm' action='result.php' method='post' 
onsubmit="return checkclick('Yes', 'No', this)"> 
<input type='text' name='mybox'> 
<input type='submit'> 
</form> 

的問題是,當用戶點擊是或否按鈕,它會回去到同一頁面。但是,如果我在'if'部分中將'return false'更改爲'return true',則單擊Submit按鈕後,頁面將直接轉到result.php,而不必等待用戶單擊Yes或No按鈕。有沒有什麼方法可以檢查用戶點擊哪個按鈕,這樣在點擊Yes之後,頁面會轉到result.php,點擊No後仍然保留在當前頁面上?

+0

你的問題是,在大多數情況下,回答在這裏: http://stackoverflow.com/a/3561141/1228942 – JoelPrz

+0

@JoelPrz謝謝,是該解決方案解決了我的問題。唯一的區別是我需要用'theForm.submit();'替換'window.open(...);',以便可以傳遞表單數據。 – LaBird

回答

2

jQuery對話框有選項buttons它可以用來描述所需的按鈕和它的動作。

function checkclick(button1, button2, theForm) { 
    var val; 
    val = theForm.mybox.value; 
    v = parseInt(val) || 0; 

    if (v >= 1000) { 
     $('#dialog').dialog({ 
     autoOpen: true, 
     modal:true, 
     buttons:{ 
      "Yes":function() { 
       alert('Yes has been clicked'); //Your coding here 
      }, 
      "No": function() { 
       $(this).dialog("close"); 
      } 
     } 
     }); 
     $('#dialog_link').click(function() { 
      $('#dialog').dialog('open'); 
     }); 
     return false; 
    } 
    return true; 
} 
+0

我相信你的上面的代碼,涉及'if'之前'btns'的行可以被刪除。 – LaBird

+0

謝謝。我現在更新了代碼。 – Pugazh

0

我沒有「聲譽」來評論你的後續行動,所以我不得不作爲答覆發佈。在協議中違反道歉。

如果我正確理解你的目標,你只需要有條件地提交表格。我相信,如果用戶決定表單提交時間過長,則可以通過防止默認行爲來實現此目的。事情是這樣的:

<form id="target" action="destination.html"> 
    <input type="text" value="string value"> 
    <input type="submit" value="Submit"> 
</form> 

$("#target").submit(function(event) { 
    if (//result of dialog is false) { 
    event.preventDefault(); 
    } else { 
    return; 
    } 
}); 
+0

我在這裏得到你的意思,這個解決方案是禁止用戶輸入的大量數據被提交。我想要的是要求用戶確認,如果用戶點擊「是」,則仍然會提交大量數字。事實上,上述評論中包含的解決方案(http://stackoverflow.com/a/3561141/1228942)就足夠了。 – LaBird

相關問題