'Is it possible to use same form for multiple categories data submission. If possible what would be the implementation logic?

Am creating a small project to manage my anime, manga, movies. Local json file is used as database. Able to render the data of diff categories but unable to submit the data conditionally.

Code relevent to the actual problem

index.html

//Tab Links For displaying data on click
<div>
    <button class="active" data-id="anime">Anime</button>
    <button data-id="manga">Manga</a>
    <button data-id="movies">Movies</a>
</div>

// Tab Panels with main content
<div>
    <div class="active" id="anime">
        Anime Content   
    </div>
    <div id="manga">
        Manga Content
    </div>
    <div id="movies">
        Movies Content  
    </div>
</div>

// form to add data
<form class="addData">
    <input type="text" id="id">
    <input type="text" id="title">
    <button type="submit">Submit</button>
</form>

index.js

// rendering data conditionally on click 
const renderData = async (id = 'anime') => {
    let uri = `http://localhost:3000/${id}`
    let template = ''

    const res = await fetch(uri)
    const data = await res.json()

    data.forEach(d => {
    template += `
        <div>${d.id}</div>
        <div>${d.title}</div>
    `
    })
    
    $(`#${id}`).html(template)

}

renderData()

// Adding data to json file
const addData = async (e,id = 'anime') => {
    e.preventDefault()

    const doc = {
        id: $('#id').val(),
        title: $('#title').val()
    }

    await fetch(`http://localhost:3000/${id}`, {
        method: 'POST',
        body: JSON.stringify(doc),
        headers: { 'Content-Type': 'application/json' }
    })

}

$('.addData').on('submit', addData)

// Adding click event to tab links and getting data-id value, Passing id value as argument to the above functions
$('.nav-link').click((e) => {
    let id = e.target.dataset.id
    $('.heading').text(id)
    renderData(id)
    addData(e, id)
})

db.json

{
    "anime": [
         some data...
    ],
    "manga": [
         some data...
    ],
    "movies": [
         some data...
    ]
}

Implementing above code just adds data to anime object in json file. but when I click on other tab links page gets reload and shows me anime page only along with adding null id, title fields in anime.

What I want to achieve is to add data to anime when am in anime tab panel or to manga when am in manga tab panel using single form. Is it possible to achieve this with single form. if so how ?

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source