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>