Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make some special words read-only in the text area or text field

I have two fields . Textarea and input type text . In these there are some tags like <firstname> i want to make these uneditable for the users. and if he tries to delete the whole tag will remove. here is the Js fiddle

I am trying with this

$(function () {
            var tb = $("#t").get(0);
            $("#t").keydown(function (event) {
                var start = tb.selectionStart;
                var end = tb.selectionEnd;
                var reg = new RegExp("(<.+?>)", "g");
                var amatch = null;
                while ((amatch = reg.exec(tb.value)) != null) {
                    var thisMatchStart = amatch.index;
                    var thisMatchEnd = amatch.index + amatch[0].length;
                    if (start <= thisMatchStart && end > thisMatchStart) {
                        event.preventDefault();
                        return false;
                    }
                    else if (start > thisMatchStart && start < thisMatchEnd) {
                        event.preventDefault();
                        return false;
                    }
                }
            });
        });

but it is not working .

it is working for only that if cursur is on start of the tag then it is not editable . But if cursur is on end of tag then this is editable . I want to make it fullu uneditable.

like image 248
Manoj Dhiman Avatar asked May 02 '15 07:05

Manoj Dhiman


1 Answers

its done . I just add +1 to the start and end selector . and it works .here is the working link JSfiddle html code is

<input type="text" class="tag-check" value="<tagname> this is just a check" >
<textarea id="t" class="tag-check" rows=5 cols="80">Hello this is a test <companyname> 

        <lastname> this part is editable <firstname>     

    </textarea>

js code is

$(function () {


            $(".tag-check").keydown(function (event) {
                var tb = $(this).get(0);
                var start = tb.selectionStart;

                var end = tb.selectionEnd;
                var reg = new RegExp("(<.+?>)", "g");
                var amatch = null;
                while ((amatch = reg.exec(tb.value)) != null) {
                    var thisMatchStart = amatch.index-1;
                    var thisMatchEnd = amatch.index + amatch[0].length+1;
                    if (start <= thisMatchStart && end > thisMatchStart) {
                        event.preventDefault();
                        return false;
                    }
                    else if (start > thisMatchStart && start < thisMatchEnd) {
                        event.preventDefault();
                        return false;
                    }
                }
            });
        });
like image 165
Manoj Dhiman Avatar answered Oct 23 '22 05:10

Manoj Dhiman