How to mark words that match words from a list in a django form's textarea using javascript?

I have the following form:

class TestForm(Form):
    testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here')

Rendered to my template along with the following list as context:

dummy_list = ['hi', 'hello']

I'm trying to make a button which I can click in my template which makes words in the form bold if they are contained within the list.

JS:

<script type="text/javascript">
function Mark_words(id)
{
    var form_content = document.getElementById(id);
    var dummylist = {{ dummy_list }}
    var new_form_content = ""
    for(var x in form_content.value) {
        if ( dummylist.indexOf(x) > -1 ){
            x = x.bold();
            new_form_content += x + " ";
        } else  {
            new_form_content += x + " ";
        }

    }
    form_content.innerText = new_form_content;
}
</script>

And the following button:

<button type = "submit" class ="btn btn-info" value = "Click" onclick="Mark_words('test')">Mark words</button>

Unfortunately, nothing happens when I click the button. What am I doing wrong?

The problem is how you're iterating through the content of the textarea.

for(var x in form_content.value) will iterate through the content one character at a time and because you're using in, you'll get the indices of the characters, not the characters themselves.

What you need to do is split the string on spaces, so you're iterating through words, and change in to of so you get the string and not the index of the string:

for(var x of form_content.value.split(' '))

function Mark_words(id)
{
    var form_content = document.getElementById(id);
    var dummylist = ['hi', 'hello'];
    var new_form_content = ""
    for(let x of form_content.value.split(' ')) {
        if ( dummylist.indexOf(x) > -1 ){
            x = x.bold();
            new_form_content += x + " ";
        } else  {
            new_form_content += x + " ";
        }

    }
    form_content.innerText = new_form_content;
}
<button type = "submit" class ="btn btn-info" value = "Click" onclick="Mark_words('test')">Mark words</button>
<textarea id="test">hello there I am a new type of automated washing machine</textarea>

Back to Top