<input type="text" size="25" maxlength="50" value="initial value"> //创建多行文本框 <textarearows="25"cols="5">initial value</textarea> //用使用value属性读写文本框 let textbox=document.forms[0].elements["textbox1"]; textbox.value="Some new value";
选择文本
select()用于全选文本
1 2 3 4 5 6
let form=document.getElementById("myForm"); let textbox=form.elements[0]; textbox.addEventListener("focus",(event)=>{ event.target.select(); console.log(`Text selected:${textbox.value}`); });
setSelectionRange()用于部分选择文本
1 2 3 4 5 6 7
let form=document.getElementById("myForm"); let textbox=form.elements[0]; textbox.addEventListener("focus",(event)=>{ event.target.select(); textbox.setSelectionRange(0,1); console.log(`Text selected:${textbox.value}`); });
</form> let inputIds=["textTel1","textTel2","textTel3"]; for(let id of inputIds){ let textbox=document.getElementById(id); textbox.addEventListener("keyup",(event)=>{ let target=event.target; if(target.value.length==target.maxLength){ let form=target.form; for(let i=0,len=form.elements.length;i<len;i++){ if(form.elements[i]==target){ if(form.elements[i+1]){ form.elements[i+1].focus(); } return; } } } }); };