简体   繁体   English

如何将光标设置为 html 文本输入字段?

[英]How can I set cursor into html text input field?

For a Flask app I am trying to set the cursor into an input text field in a form.对于 Flask 应用程序,我试图将光标设置到表单中的输入文本字段中。 The form looks like this:表格如下所示:

<form method="get" autocomplete="off">
        <div class="row">
            <div class="four columns">
                <label for="from-currency">Exchange:</label>
                <input type="text" placeholder="currency to exchange from" value="{{ from_curr }}" name="from_currency" id="from-currency" class="input-field"/>
            </div>
            <div class="four columns">
                <label for="to-currency">To:</label>
                <input type="text" placeholder="currency to exchange to" value="{{ to_curr }}" name="to_currency" id="to-currency" class="input-field"/>
            </div>
            <div class="four columns">
                <label for="calculate-button">&nbsp;</label>
                <input type="submit" value="Calculate" id="calculate-button" class="input-field">
            </div>
        </div>
    </form>

I tried using JavaScript (element.focus();), but it did not move the cursor into my input field.我尝试使用 JavaScript (element.focus();),但它没有将光标移动到我的输入字段中。

<script>
    function submit_param(inp) {
        inp.addEventListener("input", function(event) {
            var val = this.value;
            var urlParams = new URLSearchParams(window.location.search);
            urlParams.set(inp.name, val);
            var queryString = urlParams.toString();
            history.pushState({}, "", "?"+queryString);
            location.reload();
            inp.focus();
        });
    }
    submit_param(document.getElementById("from-currency"));
    submit_param(document.getElementById("to-currency"));
</script>

What am I doing wrong, or how else can I move the cursor back into the input filed at the end of my script block?我做错了什么,或者我怎样才能将光标移回脚本块末尾的输入字段?

How can I set cursor into html text input field?如何将光标设置为 html 文本输入字段?

<input type="text" autofocus>

The autofocus attribute is a boolean attribute. autofocus 属性是一个布尔属性。

When present, it specifies that an element should automatically get focus when the page loads.当存在时,它指定一个元素应该在页面加载时自动获得焦点。

Hope this helps.希望这可以帮助。 Good luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM