2017-04-13 28 views
0

我有兩種形式的登錄頁面,只有一種形式在tme中可見。第一種形式是一種年齡驗證形式,如果符合條件,我使用jQuery .toggle()切換到下一個表單。在頁面加載,好UX我使用.focus()擺在第一個窗體域的光標這行代碼:$("input[name='month']").focus();JS - 聚焦/選擇切換後的光標

// Focus cursor on first input field 
 

 
$("input[name='month']").focus(); 
 

 
var age = 19; 
 
// After calculating age based on user input, toggle the elements 
 

 
if (age >= 18) { 
 
    $('#age-verification').toggle(); 
 
    $('#subscribe').toggle(); 
 
} else { 
 
    $('#age-verification').html('<h2>Sorry, you must be at least 18 years old.</h2>'); 
 
}
<div id="age-verification"> 
 
    <h2>Must be 18, please verify age</h2> 
 
    <input type="number" name="month" /> 
 
    <input type="number" name="day" /> 
 
    <input type="number" name="year" /> 
 
    <button id="age-gate-submit">Submit</button> 
 
</div> 
 

 
<form id="subscribe" action="#" method="post"> 
 
    <input type="text" name="email" /> 
 
    <input type="text" name="zip" /> 
 
    <button id ="subscribe" type="submit">Submit</button> 
 
</form> 
 

 
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

我如何可以使用.select()focus()或其他方法將光標置於.toggle()事件之後的第二個表格<input type="text" name="email" />的第一個字段中?我試過在.toggle()之後直接放置.focus()事件,這似乎合乎邏輯但不成功。

回答

1

您需要先隱藏訂閱形式:

$('#subscribe').hide(); 

工作演示:http://jsbin.com/kihepujewi/edit?html,js,output

+0

感謝您的迴應,它的工作原理,但我有點困惑。我的div已經設置爲'display:none',那麼爲什麼我需要首先使用'.hide()'? –

+1

@JoelB我相信我所做的唯一其他真正的改變是對您所說的通過用戶輸入來檢索的年齡變量進行硬編碼。 –

+0

我的代碼在我身邊,但在這裏舉例說明,這絕對有幫助。謝謝! –