'Alpine.js When I re-render with x-for, the checked of checkbox is removed
<script src="//unpkg.com/alpinejs" defer></script>
<style>
input[type=checkbox]:checked + span {
color: red;
}
</style>
<div x-data="taggle()" class="" style="height: 500px;margin:30px;">
<input x-model="text" type="text" id="tag" list="taglist" placeholder="Enter a tag" style="width:15em;">
<button id="addTag" @click="addTag()">addTag</button>
<div id="div_tags"></div>
<datalist id="taglist">
<option value="html"></option>
<option value="PHP"></option>
<option value="JavaScript"></option>
<option value="CSS"></option>
</datalist>
<template x-for="(tag,index) in tags" :key="index">
<label style="margin: 0px 10px">
<input type="checkbox" name="tags[]" :id="tag.id" :value="tag.text" :checked="tag.isChecke"
@change="removeTag($event,index)">
<span x-text="tag.text"></span>
</label>
</template>
</div>
<script>
const taggle = () => ({
text: '',
tags: [],
addTag() {
if (this.text.trim() == '') return;
this.tags.push(this.newTag());
},
newTag() {
tag = {
id: badId(),
text: this.text,
isChecke:true,
};
this.text = '';
return tag;
},
removeTag($event,index) {
console.log($event.target.checked);
this.tags.splice(index, 1);
},
});
function badId() {
return (Math.random() * 100).toFixed(0);
}
</script>
https://codepen.io/y0sh1m0t0/pen/eYeyJod
- added tag
- Removed first tag. For some reason, the second checkbox is unchecked.
- The checkbox in the code are checked, but they do not work.
- If you remove the checkmark from behind, no problem will occur.
It would be helpful if you could see the images for more details.
The cause of this is unknown. I can't find a solution.
Solution 1:[1]
I modified the code as follows, and it worked.
//correction
<input type="checkbox" name="tags[]" :id="tag.id" :value="tag.text" checked
@change="removeTag($event,tag)">
//correction
removeTag($event,tag) {
// console.log($event.target.id,tag.id);
this.tags = this.tags.filter(t => t.id !== tag.id);
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | y0shim0t0 |
