I have two components, Question.svelte and QuestionList.svelte. The Question component has a clear button which will clear the selection of its options, which are radio buttons. The QuestionList component has a clear button which will clear all the selections.
When I iterate over the object and console.log it in the start, it shows the objects correctly as {id: 1, text: “….”, options = […]}.
When I try to log the index from the Question component, it gives me the questionIndex in the form of “1, ” instead of just a number like “1”.
I want to pass the index in the loop as “1” instead of “1, “. It adds a comma automatically.
QuestionList.svelte
<script>
import Question from './Question.svelte';
export let questions = [
{ id: 1, text: 'What is your favorite color?', options: ['Red', 'Blue', 'Green'], selectedOption: "" },
{ id: 2, text: 'What is your favorite animal?', options: ['Cat', 'Dog', 'Bird'], selectedOption: "" }
];
function handleOptionChange(questionIndex, selectedOption) {
questions[questionIndex].selectedOption = selectedOption;
}
function clearAllSelections() {
questions = questions.map((question) => ({...question, selectedOption: ""}));
console.log('Cleared all selections');
console.log(questions);
}
function clearSingleSelection(e) {
console.log(e);
const questionIndex = e.detail;
console.log(`Cleared Single: ${questionIndex}---`);
console.log(questions);
questions[questionIndex].selectedOption= "";
}
console.log(`QuestionList.svelte`, questions);
</script>
{#each questions as question, index}
<Question
questionId={question.id}
question={question.text}
options={question.options}
selectedOption={question.selectedOption}
questionIndex = {Number(index)},
on:clearSingleSelection={clearSingleSelection}
/>
{/each}
<button on:click={clearAllSelections}>Clear All</button>
Question.svelte
<script>
import { createEventDispatcher } from 'svelte';
export let question, questionId, questionIndex;
export let options = [];
export let selectedOption = '';
const dispatch = createEventDispatcher();
// Function to handle option change
function handleChange(event) {
const selectItem = {
id: questionId,
selectedOption: event.target.value,
}
console.log(`From Question.svelte, changed ${questionIndex}--`);
dispatch('optionChange', selectItem);
}
function handleSingleClear() {
dispatch('clearSingleSelection', questionIndex);
console.log(`From Question.svelte, cleared ${questionIndex}--`);
}
console.log(`Question Index from Question.svelte: ${questionIndex}---`);
</script>
<div class="question-item">
<div class="question-section">
<p>{question}</p>
</div>
<div class="option-section">
{#each options as option}
<input
type="radio"
name={questionId}
value="{option}"
checked={option === selectedOption}
on:change={handleChange}
/>
<label for="{option}">{option}</label>
{/each}
</div>
<button type="button" on:click={handleSingleClear}>Clear</button>
</div>