Skip to content

Instantly share code, notes, and snippets.

@PierreLebedel
Created January 10, 2025 11:25
Show Gist options
  • Save PierreLebedel/894ecf98ce1645a7fc947feab6d53dfd to your computer and use it in GitHub Desktop.
Save PierreLebedel/894ecf98ce1645a7fc947feab6d53dfd to your computer and use it in GitHub Desktop.
Phone input with intlTelInput + Livewire + Alpine
import intlTelInput from 'intl-tel-input';
import { fr } from "intl-tel-input/i18n";
window.setupPhoneInput = function (element, options) {
return intlTelInput(element, {...{
loadUtils: () => import("intl-tel-input/utils"),
i18n: fr,
nationalMode: false
}, ...options});
}
<form wire:submit="submit">
<x-phone wire:model="phone" label="Numéro de téléphone" required />
</form>
@props(['type'=>'tel'])
<div x-data="{
iti: null,
initIntlTelInput() {
this.iti = setupPhoneInput(this.$refs.phoneInput, {
initialCountry: 'fr'
});
this.$refs.phoneInput.addEventListener('countrychange', () => {
this.updateInternationalNumber();
});
this.$refs.phoneInput.addEventListener('input', () => {
this.updateInternationalNumber();
});
},
updateInternationalNumber() {
$wire.{{ $attributes->whereStartsWith('wire:model')->first() }} = this.iti.getNumber();
}
}" x-init="initIntlTelInput()">
<div wire:ignore>
<x-front.form.input {{ $attributes->whereDoesntStartWith('wire:model')->merge(['type'=>$type]) }} x-ref="phoneInput" />
</div>
<input type="hidden" x-ref="phoneOutput" wire:model.live="{{ $attributes->whereStartsWith('wire:model')->first() }}" />
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment