Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

チェックされているチェックボックスの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
  ]
]);
kazu56
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした