Created
January 10, 2025 11:25
-
-
Save PierreLebedel/894ecf98ce1645a7fc947feab6d53dfd to your computer and use it in GitHub Desktop.
Phone input with intlTelInput + Livewire + Alpine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form wire:submit="submit"> | |
<x-phone wire:model="phone" label="Numéro de téléphone" required /> | |
</form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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