1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPとJavaScriptを使ったプルダウンを覚えたので記録しておく

Posted at

#PHPを使ったプルダウンを覚えたので記録しておく。
一部分を抜き出しているので非常にわかりにくいかもしれませんが...
PHP、JavaScript、Ajax、jsonを使用。

PHPファイルその1

<select name="category" size="1" id="category">
  <option value="大型犬" data-filter="大型犬">大型犬</option>
  <option value="中型犬" data-filter="中型犬">中型犬</option>
  <option value="小型犬" data-filter="小型犬">小型犬</option>
</select>
<select name="subcategory" size="1" id="subcategory">
</select>

サブカテゴリにデータを入れていきます。

PHPファイルその2

<?php

if(isset($_GET['category']) == true){
  $category = $_GET['category'];
}

//json形式で項目を入力しておく
if($category  == '大型犬'){
  $array = "[{\"name\": \"ゴールデンレトリバー\", \"value\": \"ゴールデンレトリバー\"},{\"name\": \"ラブラドールレトリバー\", \"value\": \"ラブラドールレトリバー\"},{\"name\": \"サモエド\", \"value\": \"サモエド\"}]";
}else if($category == '中型権'){
  $array = "[{\"name\": \"コーギー\", \"value\": \"コーギー\"},{\"name\": \"柴犬\", \"value\": \"柴犬\"}]";
}else if($category == '小型犬'){
  $array = "[{\"name\": \"チワワ\", \"value\": \"チワワ\"},{\"name\": \"マルチーズ\", \"value\": \"マルチーズ\"}]";
}

header('Content-Type: application/json; charset=utf-8');
print($array);


  //カテゴリ設定
  $('#category').on('change', function (event) {
    category();
  });
});

//カテゴリ設定の関数
function category() {
  $.ajax({
    url: '***ファイル名を入力***',
    type: 'GET',
    data: {
      category: $('#category').val(),
      select: 'subcategory',
    },
    dataType: 'json',
    cashe: false
  }).done(function (data) {
    const target_number = event.target.value;
    const subcategory = $('#subcategory');
    const data_sub = $('#category').children().eq(target_number).data(subcategory);
    subcategory.empty();
    for (let i = 0; i < data.length; i++) {
      let option = $('<option></option>');
      option.val(data[i]['value']);
      option.text(data[i]['name']);
      subcategory.append(option);
    }
  }).fail(function (data, textStatus, error) {
    alert('error');
  });
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?