2011-02-25 71 views
1

我有這樣對我的模板Django的方式提交:Django中插入值到文本使用JavaScript

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

我一直在試圖將值插入上面使用JavaScript提交了文字,但我沒沒有太大的成功:

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

任何想法可能是什麼問題?謝謝!

+0

這只是一個鏡頭黑暗,但嘗試將腳本更改爲'document.my_form.txt_filed1.value =「我的價值」;' – zdyn 2011-02-25 16:30:53

+0

什麼是HTML輸出Django代碼? – Stofke 2011-02-25 16:33:34

+0

Django代碼的html輸出是: avatar 2011-02-25 17:02:31

回答

2

看起來像你把form-當你的領域不包含。

嘗試:

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

或者:

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

或者拿起一個JavaScript框架。我寧願寫在jQuery的:

$("input[name=txt_field_1]").val("hello") 
+0

getElementById有竅門。謝謝! – avatar 2011-02-25 17:12:24

0

這爲我工作

添加ID的形式

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

然後在js代碼

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