Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Svelte and form with dynamic inputs

$
0
0

I want to create a form to retrieve a person's name and country, but with the possibility of adding several lines of the same type on client side before submitting the form. Here is the code I use.

/* This is my Person.svelte component file */<script>  export let uniqueId;</script><div><label for="firstname{uniqueId}">Name</label><input type="text" id="firstname{uniqueId}" name="firstname[]" /><label for="country{uniqueId}">Country</label><input type="text" id="country{uniqueId}" name="country[]" />/></div>/* And this is the +page.svelte file */<script>import Person from "./Person.svelte";import { onMount } from "svelte";let idCount = 0;const addPerson = () => {  idCount++;  const Person = new Person({    props: {        uniqueId: idCount,    },    target: PersonForm,    });  };  onMount(() => {  const PersonForm = document.getElementById("PersonForm");});</script><form method="POST" id="PersonForm"><Person uniqueId={idCount} /><button type="submit">Submit</button></form><button on:click={addPerson}>Add a person</button>

I expect to have an array by putting [] in the input names but that doesn't work : in the back-end I receive something like this where I have the same name for each data :

[{ name: 'firstname[]', value: 'John' },{ name: 'country[]', value: 'Texas' },{ name: 'firstname[]', value: 'James' },{ name: 'country[]', value: 'New York' }]

Here's the backend code to get the form data :

export const actions = {    default: async ({request}) => {        const data = await request.formData();        console.log("Data : ", data);        console.log(request.formData);    }};

Do you have any ideas to get structured data from the form ?


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>