Bishnu Bhattarai
Bishnu Bhattarai

Reputation: 2910

How to get django form value in javascript without saving it into model

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 ?

Upvotes: 3

Views: 12251

Answers (3)

Aks
Aks

Reputation: 1232

try this also if you want to directly get values

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

Upvotes: 2

Jayaram
Jayaram

Reputation: 760

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();

Upvotes: 11

Aamir Rind
Aamir Rind

Reputation: 39659

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

Upvotes: 1

Related Questions