0

I am trying to select store or validate multiple items from a dropdown list but I don't how to do it. let me explain what I am trying to do... I have food quality into a json list

   <select id="locality-dropdown" name="locality" multiple="multiple" size="2">
    </select>

<script>
    var Food = //4 elements json format 
        [
           {
              "name": "food1",
              "Glc": 2,
              "Lip": 0.2,
              "Prot": 0.5,
              "IG": 20
            },
           {
              "name": "food2",
               "Glc": 4,
              "Lip": 1.2,
              "Prot": 0.7,
              "IG": 40
           },
           {
              "name": "food3",
              "Glc": 5,
              "Lip": 0.32,
              "Prot": 0.76,
              "IG": 60
           },
           {
              "name": "food4",
               "Glc": 7.5,
              "Lip": 1.5,
              "Prot": 1.3,
              "IG": 80
           }       
        ];

then I put this list in a dropdown format :

    let dropdown = document.getElementById('locality-dropdown');
    dropdown.length = 0;
    let defaultOption = document.createElement('option');
    defaultOption.text = 'Choose Food';
    
    dropdown.add(defaultOption);
    dropdown.selectedIndex = 0;
    
        let option;
        for (let i = 0; i<Food.length; i++) {
          option = document.createElement('option');
          option.text = Food[i].name;
          option.value0 = Food[i].Glc;
          option.value1 = Food[i].Lip;
          option.value2 = Food[i].Prot;
          option.value3 = Food[i].IG;
          console.log(option.value0,option.value1,option.value2,option.value3)
          dropdown.add(option);}
</script>

At that point I have a nice dropdown list box with food1 , food2, food3, food4 inside.

voila! and now what to do ?!

I need to select some of them and from these selected items, use the numbers of the list shown above to follow my math such as sum of Glc, sum of Lip etc.

I don't know if I am clear enough but let say I choose food1 and food3, then because I am choosing them, it will return later, when needed : Glc of food1 + Glc of food3 ; Lip of food1 + Lip of food3 etc - if 3 elements are selected so the same process with 3 elements. I don't know how to write the code and which technic to use whether an other json , an array of the the selected elements to do so...?

ubi
  • 41
  • 5
  • I imagine you are going to want to add an `eventListener` to the `onchange` event of your `select` element. Then display the values in your event listener callback function, this SO post may give you what you need - (https://stackoverflow.com/questions/30372235/html-select-multiple-get-all-values-at-onchange-event) – Ryan Wilson Jan 07 '21 at 03:21

2 Answers2

0

Try to make a checkbox list instead of a dropdown list:

var Food = //4 elements json format 
  [{
      "name": "food1",
      "Glc": 2,
      "Lip": 0.2,
      "Prot": 0.5,
      "IG": 20
    },
    {
      "name": "food2",
      "Glc": 4,
      "Lip": 1.2,
      "Prot": 0.7,
      "IG": 40
    },
    {
      "name": "food3",
      "Glc": 5,
      "Lip": 0.32,
      "Prot": 0.76,
      "IG": 60
    },
    {
      "name": "food4",
      "Glc": 7.5,
      "Lip": 1.5,
      "Prot": 1.3,
      "IG": 80
    }
  ];
for (var i=0;i<Food.length;i++){
CurrentFood=Food[i]
var input=document.createElement("input")
input.type="checkbox"
input.id=CurrentFood.name
var label=document.createElement("label")
label.for=CurrentFood.name
label.innerText=CurrentFood.name
document.body.appendChild(input)
document.body.appendChild(label)
document.body.appendChild(document.createElement("br"))
}

After that, attach an event listener to each checkbox listening for the "change" event. Checkbox Check Event Listener After that, whenever the event fires, find the index from the parent of the ones that are checked, get the indexed arrays from the list, and return Food[index].Glc or Food[index].Lip, or whatever you want.

Endothermic_Dragon
  • 1,147
  • 3
  • 13
  • @ Endothermic_Dragon I would prefer a chekbox dropdown if possible + if possible as well, can you show me the code (I now it is simple what you said but for me very difficult to conceptualize) of what you said, it sounds intersting to me. – ubi Jan 08 '21 at 00:59
  • By "checkbox dropdown", do you mean something like this? https://stackoverflow.com/questions/19206919/how-to-create-checkbox-inside-dropdown#answer-19207528 – Endothermic_Dragon Jan 08 '21 at 01:06
  • thank you , I really would like to use a check list dropdown but it has also to be compatible with the code that Paul Rooney wrote me... and I am not sure I can do it myself; but i have the feeling it shouldn't be that tough eventough the link you gave me , wasn't clear to me – ubi Jan 10 '21 at 20:14
0

You have a few options with regard to how you can store the individual data elements corresponding to the list elements in the options value attribute.

  1. Use array indices.
  2. Transform your data into an object keyed on the name and look it up from that.
  3. Convert the data to json and store it in the value attribute. Note: This method would mean that if you updated your Food array after the dropdown was built, then you wouldn't see the updates in the options value attributes. If it needs to update individual properties, don't use this method.

Here I've done it using json. Its trivial to change it to the other two.

<html>
    <body>
        <select id="locality-dropdown" name="locality" multiple="multiple">
        </select>
        <button id="locality-but">Submit</button>
    </body>

<script>
    "use strict"
    const Food = [{
          "name": "food1",
          "Glc": 2,
          "Lip": 0.2,
          "Prot": 0.5,
          "IG": 20
        }, {
          "name": "food2",
           "Glc": 4,
          "Lip": 1.2,
          "Prot": 0.7,
          "IG": 40
       }, {
          "name": "food3",
          "Glc": 5,
          "Lip": 0.32,
          "Prot": 0.76,
          "IG": 60
       }, {
          "name": "food4",
          "Glc": 7.5,
          "Lip": 1.5,
          "Prot": 1.3,
          "IG": 80
       }       
    ];

    const dropdown = document.getElementById('locality-dropdown');
    const defaultOption = document.createElement('option');
    defaultOption.text = 'Choose Food';
    defaultOption.disabled = true;
    
    dropdown.add(defaultOption);
    dropdown.selectedIndex = 0;
    
    document.getElementById('locality-but').addEventListener('click', (event) => {
        console.log('click');
        const dd = document.getElementById('locality-dropdown');
        const result = [];
        for(let i = 0; i < dd.options.length; i++) {
            const option = dd.options[i];
            
            if(option.selected) {
                result.push(JSON.parse(option.value));
            }            
        }
        console.log("do something with \n", result);
    })
    
    for (let food of Food) {
        const option = document.createElement('option');
        option.text = food.name;
        option.value = JSON.stringify(food);
        dropdown.add(option);
    }
</script>
    
</html>

At the end of the event listener you have an array called result which has the data for all selected options. You should be able to adapt this to fit your needs.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • This is it... thank you! It's very near of what I would like to do but I have a philosophical timing/dynamic question. In your solution, it seems when I integrate the first choice my math will start immediately, but I would like first to have all the item I have chosen then start my math; in other words to validate what I have selected.... like click on a button to say I am ok of what I have chosen ( 1.2. 3 or 4 elements) or a checkbox or both ... – ubi Jan 08 '21 at 01:21
  • bravo... perfect! Would be awesome but I don't want to insist ... if you can tell me how to transform this dropdown list into a dropdown checkbox. I had a look on the link of Endothermic_Dragon but it looks complicated and not adapted with the code you wrote me. And this is not as simple as '' – ubi Jan 09 '21 at 23:56
  • Thats a bit more complex. It's obviously not a standard component so it involves a bit more code. You should check out bootstrap css to see if anything fits the bill. I found [this](https://mdbootstrap.com/snippets/jquery/mdbootstrap/821050#html-tab-view) which looks simple enough. – Paul Rooney Jan 10 '21 at 00:01
  • glurps ... not for me ....I asked this question because I use phonegap to put the js code on the phone. The thing is there is no ctrl+click like a pc to select multiple. So I thought about a checkbox, but if you have an other idea, welcome. – ubi Jan 10 '21 at 03:15
  • There are no doubt we’ll established techniques for dealing with this for mobile web. It sounds like you don’t know much about js or css, so probably the best bet it to use libraries like bootstrap to give you ready made components. – Paul Rooney Jan 10 '21 at 08:50
  • You can't leave me like this lol .... pleaaaase answer me I can't use your code under jquery, I mean no console is shown after selection here is the link I have posted https://stackoverflow.com/questions/65694132/how-to-make-a-dropdown-list-using-json-format-compatible-with-jquery?noredirect=1#comment116159931_65694132 – ubi Jan 21 '21 at 02:18
  • So nice of you. Well the new question is in the link I wrote above. Waiting for your input. Have a nice vacation – ubi Jan 21 '21 at 17:34