【问题标题】:Displaying a text field along with radio through Django form通过 Django 表单显示文本字段和收音机
【发布时间】:2018-09-13 18:22:01
【问题描述】:

假设我有一个包含 2 个字段的模型。一个字段是单选按钮Choice1、Choice2 和Other 的选择字段,下一个是Other,这是一个文本字段,我希望“其他”文本框仅在单选按钮中选择“Other”时才显示/启用。

【问题讨论】:

    标签: django forms django-models django-forms


    【解决方案1】:

    这个问题不属于 django-forms 类别。这更适用于前端类别。从 django 服务器发送的所有内容都是静态的。当然,您可以编写一个表单类并覆盖它的模板。此外,您可以将 js 脚本直接连接到表单类。这很方便,但不规范。只需编写 JS 脚本或使用 JQuery,当您选择特定选项时,它将激活该字段。 我为你写了一个小例子,说明如何做到这一点。 希望对您有所帮助。

    $('input[type=radio][name=choices]').change(function() {
    	$('input[type=text][name=other]').prop(
      	'disabled',
        function(i, v) {
        	return !v;
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <p><input name="choices" type="radio" value="choice1">Choice 1</p>
      <p><input name="choices" type="radio" value="choice2">Choice 2</p>
      <p><input name="other" type="text" disabled></p>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-08
      • 2012-01-02
      • 1970-01-01
      • 2022-07-01
      • 2021-10-18
      • 2021-11-10
      • 2017-07-29
      • 2020-10-24
      相关资源
      最近更新 更多