0

I have input to insert data for a book like this

            <div class="form-group">
                <label for="Id">Id</label>
                <input type="text" class="form-control" id="Id" placeholder="Id" required>
            </div>

            <div class="form-group">
                <label for="Title">Titre du livre</label>
                <input type="text" class="form-control" id="Title" placeholder="Titre du livre" required>
            </div>

            <div class="form-group">
                <label for="Contenu">Contenu</label>
                <textarea class="form-control" id="Contenu" rows="5" required></textarea>
            </div>

            <div class="form-group">
                <label for="Prix">Prix</label>
                <input type="text" class="form-control" id="Prix" placeholder="Prix" required>
            </div>

<select multiple="" class="form-control" id="selectGenre" required="">
                    <option value="">Choisissez un genre</option>
                <option value="1">Roman</option><option value="2">Biographie</option><option value="3">Comédie</option><option value="4">Encyclique</option><option value="5">Médicale</option><option value="6">Science</option><option value="7">Culture</option><option value="8">Politique</option></select>

A book has an id/title/content/price and it can have one or several genres

I recover each value to insert it in JSON to launch a POST request.

JSON example of a book with only one genre

{"Id":1,"Title":"FluconazoleE","Contenu":"nonummy ultricies ...","Prix":19,"Genre":[{"Id":6,"Nom":"Science"}]}

JSON example of a book with several genres

{"Id":1500,"Title":"FluconazoleE","Contenu":"nsenectus et ...","Prix":19,"Genre":[{"Id":6,"Nom":"Science"},{"Id":2,"Nom":"Biographie"}]}

My function to send a POST request

function addItem() {

const addIdTextbox = document.getElementById('Id');
const addTitleTextbox = document.getElementById('Title');
const addContenuTextbox = document.getElementById('Contenu');
const addPrixTextbox = document.getElementById('Prix');
const addGenreTextbox = document.getElementById('selectGenre');

const item = {

    id: Number(addIdTextbox.value.trim()),
    title: addTitleTextbox.value.trim(),
    contenu: addContenuTextbox.value.trim(),
    prix: Number(addPrixTextbox.value.trim()),
    Genre: [{ "Id": Number(addGenreTextbox.value.trim()), "Nom": addGenreTextbox.options[addGenreTextbox.selectedIndex].text.trim() }]
};

fetch(uriBook, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(item)
})
    .then(response => response.json())
    .then(() => {
        getItems();
        addNameTextbox.value = '';
    })
    .catch(error => console.error('Unable to add item.', error));

    alert('Votre livre a bien ete ajoute !');
    window.location.href = 'liste-livres.html';

}

The problem is to send multiple choices in the genres, I can retrieve them with this code

const addGenreTextbox = document.getElementById('selectGenre');

var idGenre = [];
var nomGenre = [];
for (var option of addGenreTextbox.options) {
    if (option.selected) {
        idGenre.push(addGenreTextbox.value.trim());
        nomGenre.push(option[addGenreTextbox.selectedIndex].text.trim());
    }
}

But my question is how to process the tables to insert them in the const item to have a JSON of a book with one or several genre

user_1330
  • 504
  • 1
  • 5
  • 22
  • Does this answer your question? [Javascript to Select Multiple options](https://stackoverflow.com/questions/1295950/javascript-to-select-multiple-options) – Randy Casburn Feb 12 '21 at 17:07
  • That I did, my question is rather how to insert it in the JSON (const item) in both cases either one genre or more @Randy Casburn – user_1330 Feb 12 '21 at 17:11

2 Answers2

2

So, you're successfully getting the values from your input elements, so we'll start by modifying your code to retrieve them:

const addGenreTextbox = document.getElementById('selectGenre');

let result = {};
for (var option of addGenreTextbox.options) {
    if (option.selected) {
        result[id] = addGenreTextbox.value.trim();
        result[Nom] = option[addGenreTextBox.selectedIndex].text.trim();
    }
}

item.Genre.push(result);

That should work for you. Let me know if you have any questions or if I missed something.

Jordan
  • 194
  • 1
  • 12
  • Thank you very much for your help, I have not thought about this solution, but the problem now is that it keeps me only the last value selected, I will try to find a solution and keep you informed – user_1330 Feb 13 '21 at 14:54
  • My goal is to generate a new dictionary for each selected value. – user_1330 Feb 13 '21 at 14:57
  • I found, I modified your answer and thank you very much. – user_1330 Feb 13 '21 at 15:13
0

This is the right solution :

const addGenreTextbox = document.getElementById('selectGenre');

let GenreChoix = []
for (var i = 0; i < addGenreTextbox.options.length; i++) {
    if (addGenreTextbox.options[i].selected) {
        let result = {};
        result["id"] = addGenreTextbox.options[i].value;
        result["Nom"] = addGenreTextbox.options[i].text.trim();
        GenreChoix.push(result);
    }
}
user_1330
  • 504
  • 1
  • 5
  • 22