Choices-js / Choices

A vanilla JS customisable select box/text input plugin ⚡️
https://choices-js.github.io/Choices/
MIT License
6.24k stars 615 forks source link

Required Must Select #1070

Open ghost opened 2 years ago

ghost commented 2 years ago

Hi Sir,

I hope you are doing well.

I have a request about REQUIRED, I wanna know how we can check js-choice If not select any value then give an error message and after selection error message hides on submit button.

Thanks

BrayanCaro commented 1 year ago

I suggest to sync the validation message of the select element with the choicesjs input, which is the only visible element.

<select id="select" required>
    <option value="">select something</option>
    <option value="a">A</option>
    <option value="b">B</option>
</select>
const element = document.getElementById('select')
new Choices(element, {
    callbackOnInit() {
        const input = element.closest('.choices').querySelector('input')
        // trigger by a form o by using element.checkValidity
        element.addEventListener('invalid', () => input.setCustomValidity(element.validationMessage))
        element.addEventListener('change', () => input.setCustomValidity(element.validationMessage))
    },
})

Note: By default, the select element is hidden with display: none, that's why the required message is not displayed