开发者

django - insert value into a text filed using javascript

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 m开发者_Python百科uch success:

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

Any idea what might be the problem? Thank you!


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")


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜