How to submit Django form using Javascript?

时间:2019-04-17 01:50:03

标签: javascript django

I have the following Django form:

class EmailForm(forms.Form):
    name = forms.CharField(...)
    email = forms.CharField(...)
    message = forms.CharField(...)

Which I then render in my HTML like so:

<div class="controls">
    {% csrf_token %}
    <div class="form-group">
        {{ form.name }}
    </div>
    <div class="form-group">
        {{ form.email }}
    </div>
    <div class="form-group">
        {{ form.message }}
    </div>
    <input type="submit" value="Say hello" onclick="sendEmail(this);">
</div>

I'm trying to disable the submit button after it's pressed. Here's my javascript function:

<script>
    function sendEmail(this1)
    {
        var name = document.getElementById("form_name").value;
        var email = document.getElementById("form_email").value;
        var message = document.getElementById("form_message").value;

        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        var result = re.test(String(email).toLowerCase());

        if (name != "" && result && message != "") {
            this1.disabled=true; 
        }
    }
</script>

When I override the onclick field in the <input> tag, the button becomes disabled as a result of the Javascript function, but the form does not submit (the page is not reloaded, Django doesn't process the POST). How do I continue the default action for the submit button after disabling it?

2 个答案:

答案 0 :(得分:4)

Your template does not have the <form></form> tags, without those there is no form to submit.

You should write:

<form id="MyForm">
    <div class="controls">
    ...
    <input type="submit" value="Say hello" onclick="sendEmail(this);">
    </div>
</form>

That should do it, but in case it doesn't (I realy think it will), you can add this to your sendEmail function:

document.getElementById("myForm").submit();

答案 1 :(得分:-1)

LinkedHashMap