Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte format text input

I’m looking to create a text input that formats the inputted value as the user inputs it. As the formatting function strips additional characters from the string the input value doesn’t update. A bit of a contrived example, repl link

<script>
    let value = "[hello]"   
    const parse = (value) => value.replace(/[\[\]&]+/g, '');
    let parsed = parse('[hello]');
    const onChange = (event) => {
        parsed = parse(event.target.value);
    };
</script>

<h1>{parsed}</h1>
<input type="text" value={parsed} on:input={onChange} />

The onChange function strips the square brackets from the string but the value in the input doesn’t update if I type brackets into the input, I assume since they are stripped the value of parsed remains the same so doesn’t trigger an update. I thought about putting it inside a key block but then I’d have to track the position of the cursor, is there another solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this instead, and look up two way data binding in Svelte.

<script>
    let value = "[hello]"   
    // strips any square brackets from string
    const parse = (value) => value.replace(/[\[\]&]+/g, '');
    let parsed = parse('[hello]');
    const onChange = () => {
        parsed = parse(parsed);
    };
</script>

<h1>{parsed}</h1>
<input type="text" bind:value={parsed} on:input={onChange} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading