mardi 27 novembre 2018

How to modify a string based on a checkbox array?

I have a function that have :
- Inputs : an array of Data

[{"position":"1","token":"Darién","tag":"PERSON"},{"position":"2","token":"Darién","tag":"PERSON"},{"position":"3","token":"Gap","tag":"PERSON"},{"position":"4","token":"Gap","tag":"PERSON"},{"position":"5","token":"make","tag":"O"}] 

I iterate that array to get the token and tag and then based on a checkbox selection (person or country ...etc) I make the token string red and show it in a div element.

 function makeNamesRed(array) {

        let result = ''

        array.forEach((element, index, array) => {
            var word = element.token;
            var tag = element.tag;

            var checkedElements = new Array();
            $("input:checkbox[name=selectionFilter]:checked").each(function () {
                checkedElements.push($(this).val());
            });

            checkedElements.forEach((element, index, array) => {

                if (word != "-LRB-" & word != "-RRB-") {

                    if (tag == element) {
                        word = "<span class='namePerson' style='color:red;' data-toggle='tooltip' data-placement='top' title='Name of a person'>" + word + "</span>";
                        result += word + " ";
                    }

                    else {
                        result += word + " ";
                    }
                }

            })
        })
        $("#editor").html(" ");
        $("#editor").html(result);
    }

The problem is that looping the selected checkbox array (checkedElements) here

else {
                        result += word + " ";
                    } 

adds the words (that are not found) every time again. like so : Darién make make make. Number of repetition in make depends on how many checkboxes are selected.

Do you have an idea how to solve that and make that better ?




Aucun commentaire:

Enregistrer un commentaire