readonly atribute binding

1,947 views
Skip to first unread message

derek johnston

unread,
Jul 15, 2011, 8:52:44 AM7/15/11
to KnockoutJS
Hi,

I have a text box that I want to make readonly depending on a boolean
in the view model which is set via checkbox

On Hold: <input type="checkbox" id="onhold_${AssetId}" data-
bind="checked: IsOnHold" />
<textarea data-bind="value: Post, attr: {readonly: CanEdit ?
'readonly': ''}" rows="2" maxlength="${MaxValue}" cols="10" id="text_
${AssetId}" />


here is my constructor

function Item(post, isOnHold, time,assetId,icon, maxValue) {
this.Post = ko.observable(post);
this.Time = ko.observable(time);
this.AssetId = ko.observable(assetId);
this.Icon = ko.observable(icon);
this.IsOnHold = ko.observable(isOnHold);
this.MaxValue = ko.observable(maxValue);
this.CanEdit = ko.dependentObservable(function() {
return !this.IsOnHold();
}, this);
}

has any one got this type of attribute binging to work

regards

Derek

rpn

unread,
Jul 15, 2011, 4:50:40 PM7/15/11
to knock...@googlegroups.com
Hello-
Browsers want to support elements that just readonly on them, so you would need a binding that adds/removes the attribute.
Here is something basic that works in IE, Chrome, and FF:

  ko.bindingHandlers.readOnly {
    updatefunction(elementvalueAccessor{
        var value ko.utils.unwrapObservable(valueAccessor());
        if (value{
            element.setAttribute("readOnly"true)
        }  else {
            element.removeAttribute("readOnly");
        }  
    }  



rpn

unread,
Jul 15, 2011, 7:08:43 PM7/15/11
to knock...@googlegroups.com
Something didn't sit right with me on this one, so I looked at it again.  As long as you set the attribute to true or false, it should work properly.


In my case, locked is a boolean, so just: 

<textarea readOnly="true" data-bind="value: text, attr: { readOnly: locked() }"  rows="5"  cols="20"></textarea

rpn

unread,
Jul 15, 2011, 7:12:05 PM7/15/11
to knock...@googlegroups.com
The attr binding does unwrap the value for each attribute, so it could be written just like: 

<textarea readOnly="true" data-bind="value: text, attr: { readOnly: locked }"  rows="5"  cols="20"></textarea
Message has been deleted

homer....@gmail.com

unread,
Feb 27, 2013, 5:25:46 PM2/27/13
to knock...@googlegroups.com
Looks like it has to be readOnly="readonly" to work in IE8.
Reply all
Reply to author
Forward
0 new messages