【问题标题】:Toggle readonly attribute in input field在输入字段中切换只读属性
【发布时间】:2013-03-26 12:59:39
【问题描述】:

我创建了一个表单。这是fiddle

默认情况下,所有字段都处于只读状态。我需要在这里做的是

  1. 点击Edit button时激活要编辑的文本字段,编辑按钮(名称和值)应变为SAVE button

  2. 编辑完成后,用户应该点击Save button,它应该再次执行第一步,这意味着将按钮更改回原始状态,即Edit,文本字段更改为readonly

最好找jquery解决方案。

提前致谢!!

【问题讨论】:

    标签: jquery button uitextfield toggle readonly


    【解决方案1】:

    获取名称为Edit 的所有元素并附加一个点击处理程序。 变量prev 是前一个输入元素,ro 是该元素的只读属性状态(真/假)。

    然后我们将只读状态设置为! ro(不是 ro),这只是意味着“将其设置为与当前状态相反的状态(如果您愿意,可以使用切换功能)”,并关注prev输入。

    最后一行使用this 定位当前单击的按钮,并根据ro 变量的状态使用三元运算符更改其文本。

    $('[name="Edit"]').on('click', function() {
        var prev = $(this).prev('input'),
            ro   = prev.prop('readonly');
        prev.prop('readonly', !ro).focus();
        $(this).val(ro ? 'Save' : 'Edit');
    });
    

    FIDDLE

    【讨论】:

    • 你能解释一下吗
    • @Sowmya - 当然,添加了解释!
    • 谢谢。还有一件事,当我完成编辑(单击保存按钮)后,我需要在按钮旁边显示一个名为“已保存”的警报。请你看看这个。
    • 正是 :) 非常感谢。
    【解决方案2】:

    最简单的:

    // binds a click-handler to inputs whose `name` attribute is equal to 'Edit':
    $('input[name="Edit"]').click(function(){
        // when the input is clicked, it looks to the previous input element
        // that has a `required` attribute, and sets its `readonly` property,
        // the `r` is the current readonly state (true or false)
        $(this).prev('input[required]').prop('readonly',function(i,r){
            // returns the value as the opposite  of what it currently is
            // if readonly is false, then it returns true (and vice-versa)
            return !r;
        });
    });
    

    JS Fiddle demo.

    并提供用于更改button的文本:

    $('input[name="Edit"]').click(function(){
        $(this)
        .val(function(i,v){
            return v === 'Edit' ? 'Finished' : 'Edit';
        })
        .prev('input[required]')
        .prop('readonly',function(i,r){
            return !r;
        });
    });
    

    JS Fiddle demo.

    【讨论】:

    • 你能解释一下吗,!r和v是什么意思
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多