SdahlSean
SdahlSean

Reputation: 583

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. 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.

<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?

Upvotes: 0

Views: 686

Answers (1)

Harshal Parekh
Harshal Parekh

Reputation: 6017

How can I set cursor into html text input field?

<input type="text" autofocus>

The autofocus attribute is a boolean attribute.

When present, it specifies that an element should automatically get focus when the page loads.

Hope this helps. Good luck.

Upvotes: 1

Related Questions