سؤال

I have a django app where user can submit a form .I have put this form inside a div (say of id='mydiv_id') which is initially invisible(by css display:none).When a user want to enter the input ,he clicks a show button on the page ,and a javascript makes the div visible by making display:block.

The fields in the form have {{myform.myfield.errors}} so that a ul class="errorlist" will be created if validation fails.

I want to keep the form visible by running another javascript if the form validation fails.The body of javascript will be just $('#mydiv_id').show();

But how should I make this run? How do you tell the javascript that django form validation failed without doing the validation inside the javascript?

I think I need to put the following in javascript body..Other than that I can't figure out how to tell it that form submission failed.

$(document).ready(function(){

..
});
هل كانت مفيدة؟

المحلول

if i understand you well

$(document).ready(function(){
    show = {% if form.errors %} true {% else %} false {% endif %}
    if (show) {
       $('#mydiv_id').show();
    }
    else {
    ....
    }

)};

نصائح أخرى

def method(request):
    if something_wrong:
        data['error'] = True
    return render_to_response('template.html', data)

and in the template.html you can add the javascript block:

{% if error %}
<script type='text/javascript'>
    //the javascript used to show the message
    $(function(){
        $('#mydiv_id').show();
    });
</script>
{%endif%}

Using javascript to do form validation is a smart thing to do, why make a call to the server if the form is not valid? You are just making extra overhead to your server by making it do form validation. If you do not need to call the server to do form validation there is no reason you should, use javascript to do that.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top