Kris
Kris

Reputation: 219

Partially read-only textbox

How to make a text-box partially readonly using angularjs/HTML attribue? For example, a textbox having default value say "+91",which is readonly and else part need to enter values.

Upvotes: 5

Views: 6055

Answers (3)

codemonkeytony
codemonkeytony

Reputation: 190

Based on Nitin's work above I created this Angular Directive that should do the trick

JSFiddle

http://jsfiddle.net/codemonkeytony/3ew5h6bf/7/

Angular

    var partialApp = angular.module("partialApp", []);

    partialApp.directive('partialReadonly', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attrs) {
                elem.on('keypress, keydown', function (event) {
                    var readOnlyLength = attrs["partialReadonly"].length;
                    if ((event.which != 37 && (event.which != 39))
                        && ((elem[0].selectionStart < readOnlyLength)
                        || ((elem[0].selectionStart == readOnlyLength) && (event.which == 8)))) {
                        event.preventDefault();
                    }
                });
                $(window).load(function () {
                    elem[0].value = attrs["partialReadonly"];
                });
            }
        };
    });

HTML

<input type="text" partial-readonly="Readonly text goes here"  />

Hope this helps

Upvotes: 5

davidcondrey
davidcondrey

Reputation: 35983

.. just because you can. Here's another option.

http://jsfiddle.net/davidcondrey/jhncLhL9/1/embedded/result/

textarea { display:inline-block;float:left;outline:0;margin:0;padding:0;resize:none; }
textarea:first-of-type { border:1px solid #000;border-right:0;}
textarea:last-of-type { border-left:0; }

<form>
    <fieldset>
        <textarea readonly="readonly" cols="2" rows="1">+91 changed</textarea>
        <textarea class="var" cols="20" rows="1">Enter value here</textarea>
    </fieldset>
</form>

or

http://jsfiddle.net/davidcondrey/955z0sc4/embedded/result/

input { text-indent:30px; }
input + span:before { position:absolute;color:#000; content:'91';left:35px;top:20px; }

<form>
    <fieldset>

        <input class="var"/><span></span>
    </fieldset>
</form>

Upvotes: 1

Nitin Kaushal
Nitin Kaushal

Reputation: 211

HTML

<input id="field" type="text" value="+91" size="50" />

<div id="output">
</div>

Javascript

var readOnlyLength = $('#field').val().length;

 $('#output').text(readOnlyLength);

$('#field').on('keypress, keydown', function(event) {
    var $field = $(this);
    $('#output').text(event.which + '-' + this.selectionStart);
    if ((event.which != 37 && (event.which != 39))
        && ((this.selectionStart < readOnlyLength)
        || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
        return false;
    }
});                    

Demo http://jsfiddle.net/Yt72H/

Upvotes: 8

Related Questions