LoginSignup
93
90

More than 5 years have passed since last update.

【jQuery】チェックされたチェックボックスを取得する

Last updated at Posted at 2014-01-30

チェックされているチェックボックスのvalueを配列で取得

html
<input type="checkbox" class="area" value="kantou">関東
<input type="checkbox" class="area" value="touhoku"> 東北
<input type="checkbox" class="area" value="hokkaidou"> 北海道
jquery
area = $('[class="area"]:checked').map(function(){
  //$(this)でjQueryオブジェクトが取得できる。val()で値をvalue値を取得。
  return $(this).val();
}).get();
//mapの結果がjQueryオブジェクトの配列で返ってくるので、get()で生配列を取得する。

console.log(area);
//['kantou','touhoku']のような形で取得できる。

チェックされているチェックボックスのvalueをクエリストリング形式で取得

jquery
area = $('[class="area"]:checked').map(function(){
  return 'area[]=' + $(this).val()
}).get().join('&');

console.log(area);
//=>クエリストリング形式で取得できる。 area[]=kantou&area[]=tohoku
jQueryでサーバへpost
$.ajax({
  url:url,
  type:'post',
  dataType:'json',
  data:area //そのままPOSTする
})
.done(function( data, textStatus, jqXHR ) {
  //省略
})  

cakephp
//リクエストが配列形式なのでそのままin条件に使用できる
$area= $this->request->data('area');

var_dump($area);
/*
array(2) {
  [0]=>
  string(3) "kanto"
  [1]=>
  string(3) "tohoku"
}
*/

$res = $this->find('all',[
  'conditions'=>[
    'area'=>$area
  ]
]);
93
90
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
93
90