How to make some special read-only words in a text area or text box

I have two fields. Textarea and input type text. They have several tags, such as <firstname> . I want to make them unedited for users. and if he tries to remove the entire tag, it is deleted. here is the js violin

I'm 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 does not work.

it only works for this, if the cursor is at the beginning of the tag, then it is not editable. But if the cursor is at the end of the tag, this is edited. I want to make this completely inconclusive.

+6
source share
1 answer

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

 <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

 $(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; } } }); }); 
+3
source

Source: https://habr.com/ru/post/986402/


All Articles