Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to make a text area partially editable? (make only portions of the text editable)

I just came across a situation in which it would be an elegant solution to have only portions of a text area (previously loaded with text) be editable while other portions are not ("greyed out", so to speak).

Is this possible at all by using javascript in general?

I would be using jQuery.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this (just an outlined idea, no code):

Devise a regex that matches your entire text. Use fixed strings for the unmodifiable parts, and use [sS]*? for the modifiable parts. Use ^ and $ to anchor your regex.

/^This is fixed text. Now something editable:[sS]*?Now fixed again.$/

Now react to the keyup event, and probably other events as well (like paste).

With every relevant event, make a check if the regex still matches.

If it doesn't, cancel the event.

Effectively, this should stop modifications to parts that are literal in the regex and thus make certain parts of your text read-only.

Don't forget to test the string on the server side as well after the form post - never trust that the client cannot send invalid values.


EDIT

You can use a regex quote function to dynamically build that regex from strings, this should save you a lot of the hassle.

function regexQuote(s) { return s.replace(/[[]^$*+?{}.|\]/g, "\$&") }

usage

var re = new Regex(
  "^" + 
  [regexQuote(fixedPart1), regexQuote(fixedPart2)].join("[\s\S].*?")
   + "$"
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...