【问题标题】:On click, hide div and remove required attribute单击时,隐藏 div 并删除所需的属性
【发布时间】:2013-02-15 02:23:20
【问题描述】:

我有一个可以出现在不同页面上的表单,根据具体情况,这些字段并不总是必需的。

我有隐藏 div 的代码,但不再需要输入字段。使用 HTML5 必需属性。无法使代码正常工作。代码如下:

$('#detailssame').click(function() {
    if($(this).is(':checked')) {
        $(\"#detailssamehide\").hide();
    } else {
        $(\"#detailssamehide\").show();
    }               
});
$('.fullboxform input[type=text], .fullboxform select').each(function() {
            $(this).removeAttr('required');
});

非常感谢所有帮助。

原来上面的代码确实可以正常工作,但是可以使用 prop 替代答案

【问题讨论】:

    标签: jquery html input attributes


    【解决方案1】:

    尝试使用prop()函数设置HTML5属性。

    $(function () {
        $('#detailssame').click(function() {
            var checked = $(this).is(':checked');
            if(checked) {
                $("#detailssamehide").hide();
            } else {
                $("#detailssamehide").show();
            }     
            $('.fullboxform input[type=text], .fullboxform select').each(function() {
                $(this).prop('required', !checked);
            });
        });
    });
    

    http://jsfiddle.net/ThsXU/

    【讨论】:

    • 根据我的阅读,设置 prop('required', false) 并不能可靠地删除所有浏览器中所需的状态。您必须使用 removeAttr('required') 在所有浏览器中获得稳定的结果。
    【解决方案2】:

    删除反斜杠足以让我以所需的效果运行您的代码。

    【讨论】:

    • 斜线在那里,因为它是由 PHP 输出的。你是对的,它确实运行了。刚刚使用控制台进一步检查,并没有意识到我有几个不是文本的必需输入。
    • 尽量不要在PHP中输出js,因为它会阻止缓存并且更容易混淆和难以维护。最重要的是,避免将一种语言的代码放入另一种语言的字符串中。
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2015-10-15
    • 2016-11-27
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多