Search code examples
javascriptangularjslodashhtml-select

Angular multi-select dropdown and lodash countby


I am kinda drawing a blank on this one facet, and I can't seem to quite figure it out.

So I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)

My question is this:

Let's say I have a pre-made object such as this:

{
    keyName1: 450,
    keyName2: 800,
    keyName3: 300
}

What I want to do is to check if the key name matches a name of an option value in my multi-select dropdown (the values come from an array, using 'ng-repeat' on the option), and if the option value matches the key, add the number value to some sort of increment variable, so I can display the total number of 'keyNames' found.

For example - if a user selects 'keyName1' the incrementer value will total 450. If a user selects 'keyName1' and 'keyName2' the incrementer value will total 1,250.

I am lost on how to accomplish this - right now it is reading only the very first item in the dropdown.

Here is the code doing that:

_.forEach($scope.widget.instance.settings.serviceContractTypes, function (type) {
     // if item in array matches what is selected in multi-select option
     if(type === $('#contractType:selected').text().trim()) {
        // do stuff
     }
});

Hope this all made sense, and thanks very much for any direction you might offer...

(does not have to utilize lodash, I'm just used to using it)


Solution

  • jQuery's :selected selector only works for HTML options: "The :selected selector works for elements. It does not work for checkboxes or radio inputs; use :checked for them." (https://api.jquery.com/selected-selector/)

    You say "I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)"

    This could be relevant. By default, an HTML option tag does not support multiple selections; it has to explicitly be created as a select multiple in order to support that. Can you share the HTML code for the option to make it clear whether that's a problem or this is a red herring?

    Also, can you echo $scope.widget.instance.settings.serviceContractTypes and share to make sure it's actually matching what's available in the text of the options?

    ADDENDUM - Wait, I think I figured it out!

    The $('#contractType:selected') selects all the selected options in #contractType and concatenates them. Then $('#contractType:selected').text().trim() trims this down to the first word, which is just the first selected option. You should do something like $('#contractType:selected').text().split(" ") and then check if each type is in the resulting list.