2012-02-28 53 views
0

我在跳過文本框時收到提醒,但當我單擊頁面時,提示也會出現。如何將焦點放在文本框上時顯示提醒?即使當我打開一個新選項卡時,警報也會出現。有沒有辦法解決這個問題?非常感謝。僅當焦點位於文本框中時纔會發出提醒

$(function() { 
    $("input").blur(function() { 
    if(!this.value) { 
     alert("Text box " + ($(this).index() + 1) + " cannot be empty."); 
     this.focus(); //Keep focus on this input 
    } 
}); 

主體部分

<input type="text" id="textbox1"/> 
<input type="text" id="textbox2"/> 
<input type="text" id="textbox3"/> 
<input type="text" id="textbox4"/> 

回答

2
$(function() { 
     $('input:text').blur(function() { 
if(!this.value) { 
    alert("Text box " + ($(this).index() + 1) + " cannot be empty."); 
    this.focus(); //Keep focus on this input 
} 
}); 
}); 

還參觀http://api.jquery.com/text-selector/

希望它幫助。

+0

對不起同樣的問題再次發生 – saroj 2012-02-28 07:52:14

+0

替換$( '輸入:文本')。模糊(函數() 用$('輸入[類型=文本]')。blur(function() – 2012-02-28 07:56:01

0
<script type="text/javascript"> 
     function getAlert(txt) { 
       if (!txt.value) { 
        alert("Text box cannot be empty."); 
        txt.focus(); //Keep focus on this input 
       } 

     }; 
    </script> 

<input type="text" id="textbox1" onfocus="getAlert(this)"/> 

我希望這能解決您的問題。

+0

它只關注那個文本框只會導致頁面完全掛起 – saroj 2012-02-28 08:14:21

0

試試這個,

$(function() { 
    $("input[type=text]").blur(function() { 
     if (!this.value && $(document.activeElement).attr("type") == "text") 
      alert("Text box " + ($(this).index() + 1) + " cannot be empty."); 
      this.focus(); 
     } 
    }); 
}); 

document.activeElement會得到你當前選中的元素,然後如果所選元素是一個文本框,你可以比較。

希望這有助於.........

相關問題