0

I am working on a django app where I made a custom view that passes a queryset of elements to the rendered html page.

In the html page I want to have an option to select a word from a select list and If the selected word matches any element from the list I got from view, I should need to display it.

I tried using Java script to read these elements into array and then use that array on chnage in select box. but it didnt work as I required.

Here is what I have done so far.

View:

from .models import words as m
def test(request):
  words = m.objects.all()
context = Context({
    'words': words, 
})
return render(request, 'newpage.html',context)

newpage.html:

<select id="sel" onChange="func();">
<option  value="" selected="selected">--none--</option>
<option value="word1">word1</option>
....
<option value="wordn">wordn</option>

</select>
<script>
function func()
{
 var e = document.getElementById("sel");
 var str = e.options[e.selectedIndex].value;
 '{% for each in words %}'
 var a="{{ each.word }}";
 if(str===a)
    {
    console.log('{{each.word }}')//or passing it to a div in html
     }
{% endfor %}
 }
</script>

what I require is If the selected element is "word1" and if the queryset "words" has "word1" in it, it should display the word in the page in any div can any one help me understand the right way to use this queryset object in the html/js.

2 Answers 2

1

Fix your script like the following, this should work for you:

<script>
function func() {
    var e = document.getElementById("sel");
    var str = e.options[e.selectedIndex].value;
    "{% for each in words %}"
        var a = "{{ each.word }}";
        if(str === a) {
            console.log("{{ each.word }}")
        }
    "{% endfor %}"
}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

my bad on syntax..yup this fixed
0

Try something like this:

<script>
    var words = [
    {% for word in words %}
        "{{ word }}",
    {% endfor %}
    ];

    function func() {
        var e = document.getElementById("sel");
        var str = e.options[e.selectedIndex].value;
        for (var word = 0; word < words.length; word++) {
            if (words[word] === str) {
                console.log(words[word]);
            }
        }
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.