I have created a form that submits via javascript but each time I submit the form the webpage scrolls to the top. How do I stop that from happening?. I have tried preventDefault() but that stops the form from submitting all together.
My form:
class myform(forms.Form):
columns = forms.MultipleChoiceField(required=False, label=False)
def __init__(self, columnList, *args, **kwargs):
self.columnList = columnList
super(myform, self).__init__(*args, **kwargs)
self.fields['columns'].widget = forms.SelectMultiple()
self.fields['columns'].choices = self.columnList
My HTML:
<p> Select tables and download as excel file:</p>
<form id="myform" method="POST" name="Tables_selected">
{% csrf_token %}
{{ form.as_p }}
<input id="mybutton" type="button" class="btn btn-info" value="Download excel" onclick="redirect()">
</form>`
Javascript:
<script type="text/javascript" >
$(function(){
$('#id_columns').change(function(){
$('#myform').submit();
return false;
});
});
function redirect() {
location.href="{% url 'download_excel' %}";
}
</script>
I have tried this, but it prevents the form from being submitted, as well as the redirect:
$(function(){
$('#id_columns').change(function(){
$('#myform').submit(function(e) {
e.preventDefault();
);
});
});