3

I created a django form and I need not to save those values in my database. But I don't know how to access those form values in javascript.

balance.html

<script>
$(document).ready(function () {
    $('.dateinput').datepicker();
    var a = document.getElementsById("{{ form.start_date }}").val;
    alert(a);
});
</script>   

<div>
    <form action="" method="POST">{% csrf_token %} Start Date: {{ form.start_date }}&nbsp;&nbsp; End Date:{{ form.end_date }}
        <br/>
        <input type="submit" name="submit" value="See Results" id="tryonce">
    </form>
</div>

But I can't get the result. How those form value can be retrieve in javascript ?

3 Answers 3

11

The {{ form.start_date }} expands to:

<input id="id_start_date" type="something">

You can always right-click and inspect the element in most of the modern browsers.

So use:

var a = document.getElementsById("id_start_date").val;

I suggest you use the jQuery version:

var a = $("#id_start_date").val();
Sign up to request clarification or add additional context in comments.

Comments

2

try this also if you want to directly get values

var start_date="{{ form.data.start_date }}"

Comments

1

The form is rendered automatically as valid html. You can access form fields by their id using the prefix id_field_name. So start_date field has id id_start_date:

var a = document.getElementsById("id_start_date").val;

You should read documentation on form rendering here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.