jQueryでcsvを読み込んでセレクトボックスにappend(例えば県選択→市区町村選択とか)
xmlをajaxで読み込んで表示するというのはよくあると思うのですが、サーバーサイドではcsvを読み込んでいるケースが多いと思います。
そのためクライアントサイドでも外部データを読み込みたい場合はcsvデータを共有して使いたいという要望がありました。
今回はcsvをjQueryで読み込んでみたいと思います。まずはDEMOサンプルページからどうぞ
普通はhtmlでパースする際はtable等で書き出す事が多いと思いますが、今回はselect
に.append()
してみたいと思います。
今回のデモの仕様としては、
1.都道府県を選択
2.選択した都道府県のCSVを読み込み、その市区町村がoptionとしてappendされる
3.市区町村を選択で2で読み込んだCSVパラメータが検索ボタンのhrefにセットされる
という仕様です。
まずはCSVの準備から
CSVに馴染みがない方の為軽く説明しますが、CSVはエクセルで作成したデータをCSV形式で書き出したものです。書き出したデータをみると下記ソースの様に「,」で文字列が区切らています。(設定で変えられる。)書き出し時の文字コード、改行コードには気をつけましょう。
埼玉県,11_0011,川越市 埼玉県,11_0012,熊谷市 埼玉県,11_0013,川口市 埼玉県,11_0014,所沢市 埼玉県,11_0015,春日部市 埼玉県,11_0016,上尾市 埼玉県,11_0017,越谷市
次にjQuery
プラグインの「jQuery CSV」を使います。
正式なページが無くなっているようなので下記にライブラリを記載しておきます。
/* Usage: * jQuery.csv()(csvtext) returns an array of arrays representing the CSV text. * jQuery.csv("\t")(tsvtext) uses Tab as a delimiter (comma is the default) * jQuery.csv("\t", "'")(tsvtext) uses a single quote as the quote character instead of double quotes * jQuery.csv("\t", "'\"")(tsvtext) uses single & double quotes as the quote character */ ; jQuery.extend({ csv: function(delim, quote, lined) { delim = typeof delim == "string" ? new RegExp( "[" + (delim || "," ) + "]" ) : typeof delim == "undefined" ? "," : delim; quote = typeof quote == "string" ? new RegExp("^[" + (quote || '"' ) + "]" ) : typeof quote == "undefined" ? '"' : quote; lined = typeof lined == "string" ? new RegExp( "[" + (lined || "\r") + "]+") : typeof lined == "undefined" ? "\r" : lined; function splitline (v) { // Split the line using the delimitor var arr = v.split(delim), out = [], q; for (var i=0, l=arr.length; i<l; i++) { if (q = arr[i].match(quote)) { for (j=i; j<l; j++) { if (arr[j].charAt(arr[j].length-1) == q[0]) { break; } } var s = arr.slice(i,j+1).join(delim); out.push(s.substr(1,s.length-2)); i = j; } else { out.push(arr[i]); } } return out; } return function(text) { var lines = text.split(lined); for (var i=0, l=lines.length; i<l; i++) { lines[i] = splitline(lines[i]); } return lines; }; } });
まずは$.get
で取得、$.csv()
で配列に変換します。
これをeachで先ほどのcsvを一行ずつ処理していく形です。「,」で区切られた文字列はそれぞれ配列として読み込まれますので、this[数字]で値を取れます。
$.get(name + '.csv',function(data){ var csv = $.csv()(data); $(csv).each(function(i){ var prefeNameCell = this[0], prefeNumCell = this[1], townNameCell = this[2], prefNumcd = '&A4='+prefeNumCell; if($.trim(prefeNameCell) == pref){ $('#' + name).find('.town select').append('<option value="" data-cd="'+ prefNumcd + '">' + this[2] +"</option>"); } }); });
読み込んだCSVの値を下記ソースのようにoption
にセットします。
if($.trim(prefeNameCell) == pref){ $('#' + name).find('.town select').append('<option value="" data-cd="'+ prefNumcd + '">' + this[2] +"</option>"); }
後はselectの.changed()
のイベント時にパラメータを取得できればお好きなように。。。
今回は取得したパラメータを足してURLになる事を想定して検索ボタンのaタグにattr()
しています。
$('.town select').change(function(){ var $prefecture = $(this).parent().siblings('.prefecture').find('select'), cdPref = $prefecture.find('option:selected').attr('data-cd'), cdTown = $(this).find('option:selected').attr('data-cd'), $linkBtn = $(this).parent().siblings('.linkBtn').find('a'); $(this).next('span').find('.customSelectInner').text($(this).find('option:selected').text()); if( $(this).find('option:selected').val() == '0' ){ $linkBtn.attr('href',''); $(this).next('span').removeClass('customSelectChanged'); } $linkBtn.attr('href',urlhost + cdPref + cdTown); });
以上になります。