javascript操作文本框2

字號:


    javascript操作文本框,包括獲取焦點,獲取值更改值等
    假設(shè)頁面forasp_cn_test.html
    <html>
    <head>
    <title>網(wǎng)站制作學習網(wǎng)javascript操作文本框</title>
    </head>
    <script language="javascript">
    var temp = new Object;
    代碼
    </script>
    <body>
    <input type = "text" id="forasp_text_cn" size="20" value="網(wǎng)站制作學習網(wǎng)">
    <textarea id = "forasp_textarea_cn" cols="10" rows="5" maxlength="10" onkeypress="return temp.check_textarea(this);">網(wǎng)站制作學習網(wǎng)</textarea>
    <input type="text" bad_word = "123" good_word="456" id = "test_goodbad" onkeypress = "" >
    </body>
    </html>
    繼續(xù),限制textarea的字數(shù)。
    temp.check_textarea = function(t_obj)
    {
    if(t_obj.value.length > t_obj.getAttribute("maxlength"))
    {
    return false;
    }
    }
    通過onkeypress事件,返回true和false來限制是否能輸入,在通過字數(shù)的判斷來決定返回的true和false。
    繼續(xù),允許/阻止文本框中的字符。
    在這里說明一下,good_word是允許的字符串,bad_word是阻止的字符串,可以對text定義沒有的屬性,也可以用getAttribute()來獲得。
    var t_obj = document.getElementById("test_goodbad");
    temp.checkgood = function(t_obj,oEvent,flag)//t_obj是表示那個text文本框,oEvent是windows的event屬性。falg是否屏蔽了粘貼,ctrl+v
    {
    oEvent = temp.formatEvent(oEvent);//參見以前的格式化event
    var goog_str = t_obj.getAttribute("good_word");//獲得應該有的字符串
    var get_char = String.fromCharCode(oEvent.charCode);//獲得鍵盤輸入的字符串
    var back_char = good_str.indexOf(get_char) == -1;//判斷鍵盤字符串是否在應該有的字符串中
    if (flag)//如果屏蔽粘貼
    {
    return back_char &&!(oEvent.ctrlKey && get_char == "v")
    }
    else
    {
    return back_char || oEvent.ctrlKey;
    }
    }
    temp.checkbad = fucntion(t_obj,oEvent,flag)
    {
    var bad_str = t_obj.getAttribute("good_word");//獲得不應該有的字符串
    var get_char = String.fromCharCode(oEvent.charCode);//獲得鍵盤輸入的字符串
    var back_char = bad_str.indexOf(get_char) == -1;//判斷鍵盤字符串是否在應該有的字符串中
    if (flag)//如果屏蔽粘貼
    {
    return back_char &&!(oEvent.ctrlKey && get_char == "v")
    }
    else
    {
    return back_char || oEvent.ctrlKey;
    }
    }
    在text的事件函數(shù)就是onkeypress = "return temp.check_goog(this,event,true)"
    這樣就驗證了輸入或者輸出 允許/阻止文本框中的字符