I have five (5) checkbox fields. I would like to make sure only one checkbox can be ticked and get the value of that checked checkbox.
Can someone help me on this? Thank you
Hey,
Lets say that you have 4 checkboxes, you can use the following code:
$w.onReady(function () {
for(let i=1 ; i < 5; i++){
$w(`#checkbox${i}`).onChange(()=>{
const checkBoxes = ['checkbox1', 'checkbox2', 'checkbox3', 'checkbox4'];
let filtered = checkBoxes.filter(item => item !== `checkbox${i}`);
filtered.forEach((checkbox)=>{ $w(`#${checkbox}`).checked = false; });
});
}
});
However, I recommend using for that purpose radio buttons which have the same functionalityâŚ
Good luck,
Tal.
then put onChange all the checkbox?
The function adds event handlers to all checkboxes already (this is why we use the for loop).
Hi Tal,
itâs not working on me
$w.onReady(function () {
for(let i=1 ; i < 5; i++){
$w(`#checkbox${i}`).onChange(()=>{
const checkBoxes = ['yellowBox', 'greenBox', 'whiteBox', 'redBox', 'orangeBox'];
let filtered = checkBoxes.filter(item => item !== `checkbox${i}`);
filtered.forEach((checkbox)=>{ $w(`#${checkbox}`).checked = false; });
});
}
});
Here is my editor page â> https://editor.wix.com/html/editor/web/renderer/edit/e59190d7-a71b-4b09-a759-68b4282a2eb3?metaSiteId=f157fc7c-10d6-4ee0-b15c-4ce6e8e056dd&editorSessionId=FFE0F41E-3B1C-4D42-8FBE-CAA8857D8682&referralInfo=my-account
Hi Chloe,
in the code Tal sent you above, which was just an example, please pay attention specifically to this line here:
for (let i = 1; i < 6; i++){
$w(`#checkbox${i}`).onChange
now $w selector used with â#â means - look for an element in the page with such an id, to apply the on change on. you however do not have elements with such ids.
you have yellowBox, greenBox etc
you just need to modify the code to match the ids
like Tal, i also recommend you choose radio buttons. the difference between radio and checkboxes is single select vs multi select
good luck,
Shlomi
Hi Shlomi,
Thank you for the kind reply. I choose the check box because it is customizable, I want specific color and name for each checkbox.
I adjust my button Idâs, and change it to âcheckbox, checkbox2, etcâ to match the code but it still donât change anything. still donât do what I want.
$w.onReady(function () {
for (let i = 1; i < 6; i++) {
$w(`#checkbox${i}`).onChange(() => {
const checkBoxes = ['checkbox', 'checkbox2', 'checkbox3', 'checkbox4', 'checkbox5'];
let filtered = checkBoxes.filter(item => item !== `checkbox${i}`);
filtered.forEach((checkbox) => {
$w(`#${checkbox}`).checked = false;
});
});
}
});
#checkbox, #checkbox2, #checkbox3, #checkbox4, #checkbox5
Hi,
the loop is from checkbox1 to checkbox6, i think you had an issue with the id of the first checkbox which was not called checkbox1
Shlomi
Hi Shlomi,
Itâs now working! thank you!
Are you able to post your updated code Chleo? I am having similar issues and cannot alter my code to find the right solution.