tbdrz
tbdrz

Reputation: 2190

Svelte: select text of input element on focus

I want to select the text of the input element on focus. I tried with bind:this={ref} and then ref.select(), but this seems only to work when i remove the bind:value from the input element. Why? and how to solve?

Many thanks!

<script lang="ts">
    import { evaluate } from 'mathjs';

    export let value: string | number = 0;
    let ref;

    function handleFocus() {
        value = value?.toString().replace('.', '').replace(',', '.');
        ref.select();
    }

    function handleBlur() {
        value = parseFloat(evaluate(value?.toString())).toLocaleString('be-NL', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    }
</script>

<input
    class="text-right"
    autocomplete="off"
    type="text"
    bind:value
    bind:this={ref}
    on:focus={handleFocus}
    on:blur={handleBlur}
/>

Upvotes: 2

Views: 3886

Answers (2)

mrHaugen
mrHaugen

Reputation: 81

You can do it inline in the input tag:

<input on:focus="{event => event.target.select()}">

or pass the event to a function and do more stuff:

<script>
    function selectContentAndDoStuff (event) {
        console.log("event: ", event);
        event.target.select();
        console.log("do more stuff here")
    }
</script>

<input on:focus="{event => selectContentAndDoStuff(event)}">

Upvotes: 8

tbdrz
tbdrz

Reputation: 2190

As stated by the comment of @JHeth: I added await tick(), made the function async and it worked.

<script lang="ts">
    import { evaluate } from 'mathjs';

    export let value: string | number = 0;
    let ref;

    async function handleFocus() {
        value = value?.toString().replace('.', '').replace(',', '.');
        await tick();
        ref.select();
    }

    function handleBlur() {
        value = parseFloat(evaluate(value?.toString())).toLocaleString('be-NL', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    }
</script>

<input
    class="text-right"
    autocomplete="off"
    type="text"
    bind:value
    bind:this={ref}
    on:focus={async () => handleFocus()}
    on:blur={handleBlur}
/>

Upvotes: 1

Related Questions