How to unselect radio button of Primevue on click?

105 views Asked by At

I'm using vue3 with Primevue to develop my app. I want to unselect the radio button of Primevue on click. Is there a way to do it? This is my code for radio button.

<div class="field col-12 md:col-12 lg:col-12">
     <template v-for="currency in currencies" :key="currency.id">
            <div v-if="v$.currency.$model !== currency.code" class="flex align-items-center mb-2">
                 <RadioButton v-model="paidInType" :inputId="currency.code" name="payIn" :value="currency.code" />
                 <label :for="currency.code" class="ml-2">Pay in {{ currency.symbol }}</label>
           </div>
      </template>
</div>
2

There are 2 answers

0
Siimo On

Radio button isn't meant to be un-selectable.

Please use checkbox or toggle component for your usecase and redesign them to your need.

But if you really need to overwrite default radio button action, then adding @click method to remove the selected value if its equal to the clicked on radio button value.

0
yoduh On

From a UI/UX perspective, you're not supposed to leave radio buttons blank. It's why the PrimeVue radio component has no required prop (it's just assumed required). This behavior has been standard for decades, that a radio option must be selected, even if that option is "Not applicable" or "Prefer to not say", etc. If you really need to unselect, first consider using a different component.

If you really want to deselect a radio button, what you need to do is on selection event set the v-model back to it's default unselected value state. Since you'll need to first confirm that the new selected value was the same as the previous value you need to always track that previous value.

const paidInType = ref('');
const prevValue = ref('');

function selectRadio(value) {
  if (prevValue.value === paidInType.value) {
    paidInType.value = '';
  }
}
<RadioButton
  v-model="paidInType"
  @click="prevValue = paidInType"
  @update:modelValue="selectRadio(currency.code)"
  :inputId="currency.code"
  name="payIn"
  :value="currency.code"
/>

stackblitz demo