user9092892
user9092892

Reputation:

How can I hide a form after submission?

I was wondering how can I hide a form after submission. I tried something with JavaScript, but I keep getting a message from the form that no file was chosen.

<script type="text/Javascript">
    $('input[type="submit"]').click(function () {
        $(this).parents('#files').remove();
    });
</script>
<form id="files" method="POST" action="" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

Upvotes: 1

Views: 470

Answers (2)

Yannic Hamann
Yannic Hamann

Reputation: 5215

It appears that you struggle to get the button element with jQuery. Assign an id to your button like:

<button id="mybutton" type="submit">Submit</button>

And adjust your javascript to get the element by its id:

$(function() {
    $("#mybutton").click(function() {
        $("#files").remove();
    });
});

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient.

Also, you need to wrap the click event handler inside the $(document).ready() function.


I do not recommended to remove the form on button click. How could you be certain that the data has been submitted and processed? One solution would be to take advantage of the success_url to redirect the user to another page, but only when the form is successfully processed by the back end.

Upvotes: 1

Ele
Ele

Reputation: 33726

You already have the id, so use it.

$('input[type="submit"]').click(function () {
    $('#files').remove();
});

Upvotes: 0

Related Questions