Tobi
Tobi

Reputation: 351

Javascript validation for dynamically generated forms in Django template

I am struggling with something that is probably very basic: I need to generate a form with marks for my University database application. Each student in each module has a class got "Performance" that stores all the marks for the module. There are different assessments and the Performance class calculates the average for them.

I need to be able to enter, for example, all the marks for the first assessment, and I did that with a dynamically generated Django Form as a table in the template:

{% for performance in performances %}
    <tr>
        <td>
            {{ performance.student }}
        </td>
        <td>
            {% if to_mark == 1 %} 
                <input type="text" class="input-mini" name="{{ student.student_id }}" value="{{ performance.assessment_1 }}">
            {% else %}
                {{ performance.assessment_1 }}
            {% endif %}
        </td>

       And the same for the other assessments (to_mark gets passed on by views.py to indicate which assessments needs to be marked here)

I have failed to use Inlineformfields and therefore decided to generate a form dynamically and validate it with Javascript, also because the validation is simple (has to be a number between 1 and 100), and also because I want to use Javascript to calculate the average on the fly.

My problem is that I have no clue about Javascript. All the tutorials (like this one http://www.w3schools.com/js/js_form_validation.asp) use the name of the form field in the Javascript function, but in my case that name is dynamically generated, so that I can access it easily in the views.py:

if student.student_id in request.POST:
    tmp = request.POST[student.student_id]
    try:
        mark = int(tmp)
        if mark in range(0, 100):
        performance = Performance.objects.get(student=student, module=module)
        if to_change == 1:
            performance.assessment_1 = mark
       ...and so on for the other assessments
    except ValueError:
        pass (in case someone accidentally enters a letter and not a number)

Is there a way I can use Javascript to address my form fields? Or should I use a different approach than taking the student_id as the name to read it out? How could I do that?

Thanks, Tobi

Upvotes: 1

Views: 1213

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

There are at least 3 ways to get to the form fields using JavaScript:

By ID, by CSS class or by DOM traversal. If you're not familiar with JavaScript, I would suggest finding a django-friendly client-side form validator like: https://code.google.com/p/django-ajax-forms/

Upvotes: 1

Related Questions