javascript学习指南_javascript 使用DOM设置文本框、单选按钮、复选框、下拉菜单

更新时间:2020-03-11    来源:Dom教程    手机版     字体:

【www.bbyears.com--Dom教程】

使用DOM设置文本框



1.控制用户输入的字符个数
对于单行文本框和密码输入框,可以利用maxlength属性控制用户输入的字符个数。
对于多行文本,maxlength为自定义属性,其值最多输入的字符的个数,在onkeypress事件发生时则调运返回LessThan()函数返回值,函数如下



详细代码

<script language="javascript">
function LessThan(oTextArea){
//返回文本框字符个数是否符号要求的boolean值
return oTextArea.value.length < oTextArea.getAttribute("maxlength");
}
</script>











2.设置鼠标经过自动选择文本

首先是鼠标经过时自动聚焦 onmouseover = "this.focus"

其次是 onfocus = "this.select()"
代码实例:





对于多个代码实例,可以使用以下代码进行聚焦


<script type="text/javascript">
    function myFocus() {
        this.focus();
    }

    function mySelect() {
        this.select();
    }
    window.onload = function() {
        var oForm = document.forms["myForm1"];
        oForm.name.onmouseover = myFocus;
        oForm.name.onfocus = mySelect;
    }
</script>
    

        


            
            
        


        


            
            word" name="passwd" id="passwd" class="txt">
        


        


            
            
        


    



使用DOM设置单选按钮、复选框、下拉菜单


1.设置单选按钮

单选按钮在表单中即它是一组供用户选择的对象,但每次只能选一个。每一个都有checked属性,当一项选择为ture时,其它的都变为false.

先贴沙漠化一个例子:


<script type="text/javascript">
    function getChoice() {
        var oForm = document.forms["uForm1"];
        var aChoices = oForm.camera;
        for (i = 0; i < aChoices.length; i++) //遍历整个单选项表
            if (aChoices[i].checked) //如果发现了被选中项则退出
                break;
        alert("相机品牌是:" + aChoices[i].value);
    }

    function setChoice(iNum) {
        var oForm = document.forms["uForm1"];
        oForm.camera[iNum].checked = true;
    }
</script>


    相机品牌:
    


        
        
    


    


        
        
    


    


        
        
    


    


        
        
    


    


        
        
    


    


        
        
    


    


        
        
    


    


        
    


    


        
        
    




单选按钮在表单中即它是一组供用户选择的对象,但每次只能选一个。每一个都有checked属性,当一项选择为ture时,其它的都变为false.
从以上代码中看出,id和name是不同的,一组单选按钮中它们的name是相同的,只有一个被选中。id则是绑定