【问题标题】:Adding Required Attribute to Inputs in DIV On Radio Button Change在单选按钮更改时向 DIV 中的输入添加必需的属性
【发布时间】:2015-02-09 10:00:40
【问题描述】:

我的注册表单上的一段代码有问题。用户即将选择帐户类型。 (1 和 2)更改表单上所需的字段。

我已将必填字段包装在一个 div 中,以便更轻松地访问它们,但是在向输入添加所需属性时遇到了问题。

function changeAccount(input)
{
    var selected = $(input).data("type");

    if (selected == "1")
    {
        $('#at-1-inputs').slideDown(500);
        $('#at-2-inputs').slideUp(500);

        $('#at-2-inputs').find('input').each(function() 
        {
            $(this).removeAttr('required');
        });
        $('#at-1-inputs').find('input').each(function() 
        {
            $(this).addAttr('required');
        });
    }
    else
    {
        // SAME AS ABOVE IN REVERSE
    }
}

但是每当我更改单选按钮时,在我的 JS 控制台中我都会得到一个

Uncaught TypeError: undefined is not a function

我已经检查过,当单击单选按钮时,该函数肯定会被调用。

有人对这个问题有任何见解吗?

【问题讨论】:

  • $(this).prop('required', true/false); 将 required 设置为 true 或 false

标签: javascript jquery radio-button


【解决方案1】:

改变这个:

$(this).addAttr('required');

到这里:

$(this).attr('required', 'required'); 

$(this).prop('required', true);

.addAttr() 在 jQuery 中不可用。您应该使用.attr().prop() 来设置属性/属性。


function changeAccount(input)
{
    var selected = $(input).data("type");

    if (selected == "1")
    {
        $('#at-1-inputs').slideDown(500);
        $('#at-2-inputs').slideUp(500);

        $('#at-2-inputs').find('input').each(function() 
        {
            $(this).prop('required', false); // <----use .prop() instead
        });
        $('#at-1-inputs').find('input').each(function() 
        {
            $(this).prop('required', true); //<-----use .prop() instead
        });
    }
    else
    {
        // SAME AS ABOVE IN REVERSE
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2020-04-01
    相关资源
    最近更新 更多