LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】Ace Editor で入力文字数制限をする

Posted at

Ace Editor とは

  • JavaScript を使って簡単にコードエディタをHTMLに埋め込むことが出来るライブラリ

概要

  • Ace Editor に入力する際に文字数の制限を入れたい
  • 実装方法としては onChange の際にチェックを入れる

設定用関数

// 最大文字数設定用
function setAceEditorMaxLength(editor, maxLength) {
	if (!editor)	return;
	if (maxLength !== parseInt(maxLength,10)) {
		return;
	}
	editor.session.on("change",function(edt){
		var doc = editor.session.getDocument();
		var nbLines = doc.getLength() - 1;
		var Range = ace.require('ace/range').Range;
		var range = new Range(0,0, nbLines, edt.end.column);
		var text = doc.getTextRange(range);
		var textLen = text.length;
		if (textLen > maxLength) {
			var curpos = editor.getCursorPosition();
			text = text.substr(0, maxLength);
			editor.session.setValue(text);
			editor.moveCursorToPosition(curpos);
		}
	});
}

// 初期化用(設定は環境に合わせて下さい)
function initAceEditor(id) {
	var editor = ace.edit(id);
	editor.setTheme("ace/theme/crimson_editor");
	editor.setFontSize(14);

	editor.setAutoScrollEditorIntoView(true);
	editor.setOption("minLines", 5);
	editor.setOption("maxLines", "Infinity");

	editor.getSession().setMode("ace/mode/xml");
	editor.getSession().setUseWrapMode(true);
	editor.getSession().setTabSize(2);

	return editor;
}

使い方

  • javascript
	var editor4Input = initAceEditor("inputId", true);
	setAceEditorMaxLength(editor4Input , 120); // 最大120文字
  • html
	<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>

...
...
	<!-- Ace Editor -->
	<div id="inputId"></div>

以上、お疲れさまでした!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0