【问题标题】:I want to replace one form field with another when the value of another field is equal to something当另一个字段的值等于某个值时,我想将一个表单字段替换为另一个
【发布时间】:2019-08-09 14:05:34
【问题描述】:

我这里的东西不起作用。一旦选择美国,它就会摆脱该领域,即使选择其他东西也不会回到选择。

teacher_signup.html

{% block content %}
<h2>Sign Up As Teacher</h2>
<form method="post">
    {% csrf_token %}
    {% for field in form.visible_fields %}
    {{ field | as_crispy_field}}

    {% if field.name == "country" %}
        <input type="button" value="cube" onclick="getcube()"/>  
    {% endif %}

{% endfor %}
    <button class="btn btn-success" type="submit">Sign Up</button>
</form>
<script>  
    function getcube(){  
        var county=document.getElementById("id_country").value;  
        alert(county);  
    }  
    $(document).ready(function() {
    $("#id_country").change(function(){
        if (this.value=="US"){
            $("#id_state").replaceWith();
        } 
    });
});       
</script>
{% endblock content %}

forms.py

class TeacherSignUpForm(SignupForm):
    country=CountryField(blank_label='(select country)').formfield()
    # this is just doing the same thing as country=forms.CharField(max_length=20, widget=forms.Select(choices=COUNTRY_CHOICES), required=True)
    state=forms.CharField(max_length=20,required=True)

我想将状态字段替换为 state=forms.CharField(max_length=20, widget=forms.Select(choices=STATE_CHOICES), required=True, strip=True) 如果 country=="US" 并且他们选择了其他内容,那么它将只显示文本字段。

【问题讨论】:

  • 您希望这发生在哪里?或者什么时候。在文件加载?什么不工作?有大量代码一目了然。

标签: javascript jquery html django forms


【解决方案1】:

这就是我的处理方式:

  1. 我会在您的表单中创建两个字段(例如,带有选择小部件的 state_us 字段和带有普通文本输入小部件的 state 字段)。您最初根据要为国家/地区提供的初始值创建两个 hidden 之一(或者如果国家最初为空,则将它们都隐藏)。
  2. 在表单的clean方法中,表单绑定的地方(即提交了一些数据),可以根据国家的值设置相应的字段hidden。这样才能正确呈现有错误的表单。
  3. 同样在clean 方法中,您根据cleaned_data['country'] 验证是否填充了正确的字段。
  4. 在您的模板中,两个字段都被渲染,您的 javascript 检查国家/地区的值并隐藏“id_state_us”或“id_state”(并显示另一个)。它还应该始终将state_us 字段的选定值复制到state 字段,并在选择不同的国家/地区时将其清除。这样,提交的state 数据始终包含状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2017-05-14
    • 2013-10-08
    • 2023-01-19
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多