How to bind text input to another div on the same html page

Viewed 1498

I've made a tag list that takes user input and binds it to another input field as a list of tags. However, after weeks messing around with Javascript and JQuery the only way (and importantly an elegant way) I've been able to do it is using Brython. Unfortunately, that seems to be disabling the jinja2 template in some way so nothing is submitted to the database. So, after all that, my question is, can such a seemingly simple task be done natively in Flask?

Here is the essence of how the Brython script works https://jsfiddle.net/5nt39deo/2/ but the code that the question is about is below:

<form action="" id="homeForm" class="centered" role="form" method="post">
    {{ form1.hidden_tag() }}
    {{ form1.toppings(type="text",id="homeInput",autocomplete="off",list="topps",placeholder="Toppings...") }}
    <datalist id="topps">{% for top in topps %}<option value="{{ sym }}">{% endfor %}</datalist>
    <button action="" type="submit" id="homeAddTags" class="button">Add</button><br><br>
    {{ form1.tags(id="tagList") }}<br>
    {{ form1.agree(id="homeAgreement") }}
    {{ form1.agree.label() }}<br><br>
    <button type="reset" id="homeResetTags" class="button">Reset</button>
    {{ form1.sendtags(type="submit",class_="button",id="homeSubmit") }}<br><br>
</form>


<script type="text/python" id="script1">
    from browser import document, html, window, console, alert

    storage = []

    def addTag(e):
        item = document['homeInput'].value
        if item not in storage and item != '':
            storage.append(item)
            document['homeInput'].value = ''
            document['tagList'].textContent = storage
        else:
            alert('Tag already added.')
            document['homeInput'].value = ''

    def resetTags(e):
        storage = []
        document['homeInput'].value = ''
        document['tagList'].textContent = storage

    document['homeAddTags'].bind('click', addTag)
    document['homeResetTags'].bind('click', resetTags)
</script>
2 Answers

Check out this native javascript solution

...
 <input type="text" id="text" placeholder="Enter something" oninput="outputUpdate();">
...
<script type="text/javascript" id="script2">

function outputUpdate(e){
let currentText=document.getElementById('text').value;

document.getElementById('output').innerHTML = currentText;

</script>

https://jsfiddle.net/kalovelo/z5ngxp31/

You can try something like that which I have explained below.

<input type="text">
<div id="output"></div>

Here is the Javascript: Instead of calling a javascript function explicitly, You can simply attach a keyup event to your input box. You can check this out here Fiddle

<script type="text/javascript">
var $onKeyUpEvent = document.getElementsByTagName('input')[0];
$onKeyUpEvent.addEventListener('keyup', (v) => {
    document.getElementById('output').innerHTML = v.target.value;
})
</script>
Related