LoginSignup
0
1

More than 3 years have passed since last update.

tag-itでタグの文字数チェック・カンマ「,」区切りの文字列から自動で分割させたい

Last updated at Posted at 2020-01-28

タグ入力プラグインのtag-itを利用して、
カンマ「,」区切りの文字列を入力フォームに入れたときに
自動でタグを分割するようにしました。
また、タグは最大10個までで1つのタグの文字数は100文字の制限を付けました。

※jQueryを使っています
※前提としてnpmで必要なパッケージをインストールしています

/**
 * タグの入力フォームをコントロールする
 * @return なし
 */
$(function() {
  const $tagFrom = $('#tagForm');
  $tagFrom.tagit({
    tagLimit: 10, //タグの最大個数
    placeholderText: 'タグを追加してください',
    preprocessTag: function (val) {
      if (!val) {
        return '';
      }
      // 文字列を分割してタグ表示
      const tagList = val.split(',');
      if (tagList.length > 1) {
        for (let tagKey in tagList) {
          let tagValue = tagList[tagKey];
          // 100文字以上のタグは削除
          if (tagValue.length <= 100) {
            $tagFrom.tagit('createTag', tagValue);
          }
        }
        return '';
      } else {
        // 100文字以上のタグは削除
        if (val.length <= 100) {
          return val;
        } else {
          return '';
        }
      }
    }
  });
});

HTMLは以下の通り

<input type="text" id="tagForm" />

必要なnpmパッケージ(バージョンは現在最新)

    "jquery-tagit": "^1.0.1",
    "jquery-ui": "^1.12.1",
    "tag-it": "^2.0.0"

参考文献:
https://kotaeta.com/56812856

0
1
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
1