I am new to Svelte and web development and I hope you could point me in the right direction.
The current code belongs in a svelte component. As shown here: https://svelte.dev/repl/f0e5c30117724ec38b7d19781d2c4de6?version=3.48.0
It is supposed to show one text field by default, while allowing for an additional text field to be added and removed on dynamically added buttons. Currently, this code can dynamically add the text field, however, it cannot dynamically remove the text field on button click.
I believe there might be an error in the GetDynamicElement function. However, I am not sure where exactly. Any suggestions?
p.s. I know there are answers here that are close, but I don't think they are applicable in this situation, especially on Svelte.
<script>
var num_links = 1;
let container;
const GetDynamicElement = (value) => {
return (
'<input name = "DynamicField" type="text" size =111 id =link placeholder="Enter Next link! " value = "' +
value +
'" />' +
'<input type="button" value="Remove" on:click = {RemoveField(this)}>'
// "RemoveSuggestionCart(this)" />'
);
};
const addField = () => {
if (num_links < 2) {
console.log("addField");
const div = document.createElement("DIV");
div.innerHTML = GetDynamicElement("");
container.appendChild(div); // Append timetable space
num_links += 1;
}
};
//Removes the entire division inclusive of it's text field.
const RemoveField = (div) => {
console.log("RemoveField");
div.removeChild(div.parentNode);
num_links -= 1;
};
</script>
<div>
<input
name="DynamicField"
type="text"
size="121"
id="link"
placeholder="Enter First Link!"
/>
<div bind:this={container} />
</div>
<button on:click|preventDefault={addField}>[+ add timetable link]</button>
<style>
</style>
You can use your num_link and svelte's #each to create to inputs using svelte:
{#each Array(num_links) as _, i}
<div>
<input
name="DynamicField"
type="text"
size="121"
id={`link_${i}`}
placeholder="Enter First Link!"
/>
</div>
{/each}
Working example: https://svelte.dev/repl/04169e030b6944258cfd07af15873b48?version=3.48.0