LoginSignup
0
0

More than 3 years have passed since last update.

【jQuery Raty】1ページに複数ある星の値を取得する

Last updated at Posted at 2020-01-29

Raty とは

  • 評価値などをわかりやすく星型で表現できるツール
  • jQuery を使っている
  • 検索すると表示方法のReadmeは見かけるが、それを取得してWebアプリで受け取るまではあまり載ってない
  • https://github.com/wbotelhos/raty

image.png

実施環境

ブラウザ: chrome
フレームワーク: spring-framework

1ページに複数ある星の評価入力をする

  • 例:dd タグ ID の先頭に "raty-" をつけたものをまとめて設定
  • input type="hidden" を "raty-" の後のIDで用意しておき、raty を onClick 時に value にセット
  • ID が長くて複数あっても初期化は1つにしたい
  • ページロード完了後に実施
    $('dd[id^="raty-"]').each(function(index, element) {
        var rate = $(element).data('rate');
        $(element).raty({
            half : true,
            precision : false,
            score : rate,
            click : function (score, evt) {
                var myId = this.id;
                var matches = myId.match(/^raty-(.*)$/);
                if (matches.length != 2) { return; }
                var hiddenId = matches[1];
                $("#"+selectorEscape(hiddenId)).val(roundHalfScore(score));
            }
        });
    });

HTML側の例

  • 複数を想定しているのでIDは配列に
  • data-rate に初期表示する値を入れる(動的に入れると思いますが)
              <dd id="raty-reviewFormList[0].pointRate" data-rate="3.5" style="cursor: pointer;">
                <input id="reviewFormList[0].pointRate" type="hidden" />

利用した関数

selectorEscape (セレクタのエスケープ用)

function selectorEscape(val){
    return val.replace(/[ !"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}

roundHalfScore(四捨五入)

function roundHalfScore(score) {
    var integer = parseInt(score, 10),
        decimal = getFirstDecimal(score);

    if (decimal !== 0) {
        decimal = decimal > 5 ? 1 : 0.5;
    }
    return integer + decimal;
}
function getFirstDecimal(number) {
    var decimal = number.toString().split('.')[1],
        result  = 0;

    if (decimal) {
        result = parseInt(decimal.charAt(0), 10);
        if (decimal.slice(1, 5) === '9999') {
            result++;
        }
    }
    return result;
}

以上です。お疲れさまでした!

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