如何在 html 和 javascript 中的特定输入文本中设置光标位置

How to set cursor position in particular input text in html and javascript

本文关键字:输入 文本 位置 置光标 html javascript      更新时间:2023-09-26

我正在尝试将光标设置为选定的输入框,如果在第二个输入文本框中选择了用户而没有在第一个输入框中输入值,则光标应该转到第一个输入框。

<html>
<script>
$( "#cic_name" ).focus(function() {
                                    var luname=$("#site").val();

                                    if(luname.length>0){
                                }
                                    else{
                                            alert("please select TG value");
                                        }
                        });
</script>

<body>
ENTER TG: <input type="text" id="site" name="sitename"  placeholder="TG Name">
ENTER CIC: <input type="text" id="cic_name" name="cic"  placeholder="CiC Name">

</body>
</html>

如何在所选输入框中设置光标位置,即(id= site)如果用户在第一个输入框中没有输入任何内容。

我想知道那里是否有任何游标事件。.我不敢。

谢谢

你可以做这样的事情:

$('[name=textbox2]').focus(function(){
    if($('[name=textbox1]').val() == ''){
        $('[name=textbox1]').focus();
    }
});

工作小提琴

有一个更好的方法。试试这个

$(function(){
 if($("#sitesite").val()=="")
   $("#sitesite").focus();
 else
   $("#cic_name").focus();       
});

这在 1 行中完成: 小提琴

$( "#cic_name" ).focus(function() {
      var luname=$("#site").val();
         if(luname.length>0){
            }
           else{
           alert("please select TG value");
            $("#site").focus();
             }
            });