2

I have a django form on my template like this:

<form action="/my-page/" method="post" name="my_form">{% csrf_token %}
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.txt_filed1.errors }}
        <label for="id_txt_field1">Profile Name:</label>
        {{ form.txt_filed1 }}
    </div>
    <p><input type="submit" name='update_button' value="Update" /></p>
</form>

I've been trying to insert a value to a text filed above using javascript but I didn't have much success:

<script type="text/javascript">    
document.my_form.form-txt_filed1.value = "my value";
</script>

Any idea what might be the problem? Thank you!

3
  • This is just a shot in the dark but try changing the script to document.my_form.txt_filed1.value = "my value"; Commented Feb 25, 2011 at 16:30
  • what's the HTML output of that Django code? Commented Feb 25, 2011 at 16:33
  • The html output of the django code is: <input id="id_form-txt_filed1" type="text" name="form-txt_field1" maxlength="60" /> Commented Feb 25, 2011 at 17:02

2 Answers 2

3

Looks like you put form- in when your field doesn't contain that.

Try:

// by the way, do you notice that your label is for id_txt_field1
// while your form field says {{ form.txt_filed1 }} ? 
document.my_form.txt_filed1.value = "my value";

Or:

document.getElementById('id_txt_filed_1').value = 'hello';

Or pick up a javascript framework. I prefer writing in jQuery:

$("input[name=txt_field_1]").val("hello")
Sign up to request clarification or add additional context in comments.

Comments

0

This worked for me

added id to the form

<form action="/my-page/" method="post" id="my_form" name="my_form">{% csrf_token %}
....
</form>

then in the js code

//initialized form as a variable and then set properties
var my_form = document.getElementById("my_form");
my_form.txt_filed1.value = "my value";

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.