5

Im trying to add the asYouType function from libphonenumber-js to my svelte input using an onChange handler as I'm not sure how this can be done with 2 way binding.

I have managed to implement this but it will only format the number onBlur instead of as the user types into the input as is expeccted behaviour as seen here libphonenumber-js

How can I change my input so that it will format as the user types into it?

<script>
  import { AsYouType } from "libphonenumber-js";

  export let value = "";
  export let label = "";

  let isFocused = false;
  let isTooltipVisible = false;

  const onBlur = () => {
    isFocused = false;
    isTooltipVisible = false;
  };

  const handleChange = val => {
    if (localeKey === "dfc.removal_form.phone") {
      const asYouType = new AsYouType("US");
      value = new AsYouType("US").input(val);
    }
  };
</script>

<div class="input-container input__row {isFullWidth ? 'isFullWidth' : ''}">

  <label>{label}</label>

  <input
    id={label}
    {name}
    bind:value
    on:change={e => handleChange(e.target.value)}
    on:focus={() => {
      isFocused = true;
      isTooltipVisible = true;
    }}
    on:blur={onBlur}
    on:input={() => {
      isTooltipVisible = false;
    }}
    data-ipr-selector={dataIprSelector} />
</div>


1 Answer 1

32

Handle the input event, not the change event: https://svelte.dev/repl/bf21b14cb29e41f28efc802b56e7f152?version=3.23.1

Sign up to request clarification or add additional context in comments.

1 Comment

When you get your answer directly from the creator of the language. Awesome 😆😆

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.