1

I am building a Django app and on one of the HTML sheets I have a submit button that runs a function in views.py when clicked.

<input type="submit" id="senden" class="inputfiles"/>
<button for="senden" class="button" id="weiter_btn" >Submit</button>

But I want it to first run a javascript function on the client-side and then go on and run the function in views.py. I tried to add onclick to the button element but that didn't work.

<input type="submit" id="senden" class="inputfiles"/>
<button for="senden" onclick="example()" class="button" id="weiter_btn" >Submit</button>

Should I maybe create another hidden button that runs the js function and then somehow connect it to the submit button?


UPDATE:

I've tried the first solution to this post. Now it runs the javascript function but it doesn't go on to the function in the .py. This is the js script:

<div>
        
        <script>
            var ocr = function(event){
                event.preventDefault();

                Tesseract.recognize(
                    document.getElementById('imgde').src,
                    'deu',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_de').innerHTML = ['<input type="hidden" name="txt_voc_de" id="txt_voc_de" value="',text, '"/>'].join('');
                })

                Tesseract.recognize(
                    document.getElementById('imgen').src,
                    'eng',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_en').innerHTML = ['<input type="hidden" name="txt_voc_en" id="txt_voc_en" value="',text, '"/>'].join('');
                })
                
                
   
                
            };

            var form = document.getElementById("imgForm");
            form.addEventListener("submit", ocr, false);
        </script>
        <input type="submit" id="senden" class="inputfiles" />
        <button for="senden" class="button" id="weiter_btn" >WEITER</button>
        {% csrf_token %}
        </div>
anonimostilton
  • 170
  • 1
  • 16

1 Answers1

2

You could run the onsubmit function with preventDefault() and then call the .py in the JavaScript function, after whatever it is that you want to do before it.

Something like this:

<script>
     function beforeSubmit(event){
        event.preventDefault();
        
        //your before submit logic       
        document.getElementById("myForm").submit(); 
    }
</script>
<input type="submit" value="Click" onsubmit="beforeSubmit();" />
Timothy Alexis Vass
  • 2,526
  • 2
  • 11
  • 30