2012-07-24 22 views
2

我知道有兩個條目已經處理了這類問題,我已經看了很多,但是沒有一個看起來適用於我的情況。任何幫助,將不勝感激。如何使用表單元素使用Jquery中的回車鍵

我所擁有的是一個動態生成的表單(可以有不同數量的輸入)。我需要使用我的輸入鍵來選中它們。目前標籤鍵標籤通過元素罰款,但我的標準要求我啓用輸入密鑰。當我到了最後的輸入和我按下回車,就需要執行提交通過的標籤目前完成的動作

下面是我的HTML表單的代碼片斷,以及我的JS處理該按鍵事件

<div class="credential_form"> 
<div class="error_msg"> 
    <h4>There was a problem connecting.</h4> 
</div> 
<div class="credential_inputs"> 
    <div class="txt_wrapper"> 
     <input type="text" style="width: 130px"> 
    </div> 
    <div class="txt_wrapper"> 
     <input type="password" style="width: 130px; display: none;" class="real"> 
    </div> 
    <div class="clear"></div> 
</div> 
<div class="add_button"> 
    <a class="button" href="javascript:void(0)"><span>Add</span></a> 
</div> 
<div class="clear"></div> 
<div class="sub_input"> 
    <div class="link"> 
     <span class="sub_text">Forget your details? Go to&nbsp;</span> 
     <a class="sub_link" href="http:somewhere.com">Somewhere</a> 
    </div> 
</div> 
</div> 

出於某種原因,我的集合變量無法識別if條件中的當前元素。

var code = (event.keyCode ? event.keyCode : event.which); 

if (code == 13) { 

var $inputs = $(event.target).closest('.credential_inputs').children($(':input:visible')); 
var $addButton = $(event.target).closest('.credential_form').children($('a:first-child')); 

if ($(event.target) == $inputs[$inputs.length - 1]) { 
    $addButton.click() 
} else { 
    $(event.target).closest(".credential_inputs").nextAll('input:first').focus(); 
} 
} 

感謝

+0

由於某種原因,我看不到'length'聲明在哪裏 – Alexander 2012-07-24 17:17:59

+0

@Alexander - 我的錯誤,'length'應該是'$ inputs.length',因爲我試圖檢查我是否處於最終輸入''inputs' – user1549116 2012-07-25 08:17:00

回答

0

使用.is()在您的比較。

if($(event.target).is($inputs.last())) { ... } 

雖然,你可能要檢查你的匹配表達式爲你匹配的元素($inputs$addButton)。

0

您需要使用find(),而不是孩子的

var $inputs = $(event.target).closest('.credential_inputs').find(':input:visible'); 

的。孩子()方法.find()在。孩子(不同)只 行進的單級下調DOM樹,而.find()可以遍歷多個級別的 以選擇後代元素(孫, 等)。

這意味着$('.credential_inputs').children()只會返回您的.txt_wrapper div,並且不會進一步遍歷。

+0

感謝Brian,你的回答已經解決了問題的一部分,因爲我的變量現在似乎包含了正確的元素數量,但是我仍然無法使Tab鍵工作,因爲我的條件似乎沒有驗證。 – user1549116 2012-07-25 15:41:24

相關問題