回答編集履歴

2

chousei

2019/11/07 10:37

投稿

yambejp
yambejp

スコア116694

test CHANGED
@@ -29,8 +29,6 @@
29
29
  fetch(url+'?select_a='+s_a.value).then(res=>res.json()).then(res=>{
30
30
 
31
31
  const dom=res.map(x=>Object.assign(document.createElement('option'),{value:x.code,textContent:x.name}));
32
-
33
- var count=0;
34
32
 
35
33
  while(s_b.querySelectorAll('option').length>1){
36
34
 

1

sample

2019/11/07 10:37

投稿

yambejp
yambejp

スコア116694

test CHANGED
@@ -3,3 +3,139 @@
3
3
  であればselect_aのchangeイベントでajax(or fetch)でselect_bのリストを
4
4
 
5
5
  もってくればいいでしょう
6
+
7
+
8
+
9
+ - mypage.html
10
+
11
+ ```javascript
12
+
13
+ <script>
14
+
15
+ window.addEventListener('DOMContentLoaded', ()=>{
16
+
17
+ const s_a=document.querySelector('#select_a');
18
+
19
+ const s_b=document.querySelector('#select_b');
20
+
21
+ const url="json.php";
22
+
23
+ s_b.disabled=true;
24
+
25
+ s_a.addEventListener('change',e=>{
26
+
27
+ s_b.disabled=s_a.selectedIndex==0;
28
+
29
+ fetch(url+'?select_a='+s_a.value).then(res=>res.json()).then(res=>{
30
+
31
+ const dom=res.map(x=>Object.assign(document.createElement('option'),{value:x.code,textContent:x.name}));
32
+
33
+ var count=0;
34
+
35
+ while(s_b.querySelectorAll('option').length>1){
36
+
37
+ s_b.removeChild(s_b.querySelector('option:nth-child(2)'));
38
+
39
+ }
40
+
41
+ dom.forEach(x=>s_b.appendChild(x));
42
+
43
+ });
44
+
45
+ });
46
+
47
+ });
48
+
49
+ </script>
50
+
51
+ <select id="select_a" name="select_a">
52
+
53
+ <option value="">= 選択 =</option>
54
+
55
+ <option value="0">東日本</option>
56
+
57
+ <option value="1">西日本</option>
58
+
59
+ <option value="2">海外</option>
60
+
61
+ <option value="3">ダミー</option> <!-- select_bは空になる -->
62
+
63
+ </select>
64
+
65
+ <select id="select_b"name="select_b">
66
+
67
+ <option value="">= 選択 =</option>
68
+
69
+ </select>
70
+
71
+ ```
72
+
73
+ - json.php
74
+
75
+ ```PHP
76
+
77
+ <?PHP
78
+
79
+ $select_a=filter_input(INPUT_GET,"select_a",FILTER_VALIDATE_INT);
80
+
81
+ $a=[
82
+
83
+ [
84
+
85
+ ["code"=>"001","name"=>"営業A"],
86
+
87
+ ["code"=>"002","name"=>"営業B"],
88
+
89
+ ["code"=>"003","name"=>"営業C"],
90
+
91
+ ["code"=>"004","name"=>"開発"],
92
+
93
+ ],
94
+
95
+ [
96
+
97
+ ["code"=>"001","name"=>"営業A"],
98
+
99
+ ["code"=>"002","name"=>"営業B"],
100
+
101
+ ["code"=>"003","name"=>"開発"]
102
+
103
+ ],
104
+
105
+ [
106
+
107
+ ["code"=>"001","name"=>"営業A"],
108
+
109
+ ["code"=>"002","name"=>"営業B"],
110
+
111
+ ["code"=>"003","name"=>"開発A"],
112
+
113
+ ["code"=>"004","name"=>"開発B"],
114
+
115
+ ],
116
+
117
+ ];
118
+
119
+ $list_a=array_keys($a);
120
+
121
+ if(in_array($select_a,$list_a,true)===false){
122
+
123
+ $select_a=null;
124
+
125
+ }
126
+
127
+
128
+
129
+ if(!is_null($select_a)){
130
+
131
+ print json_encode($a[$select_a]);
132
+
133
+ }else{
134
+
135
+ print "[]";
136
+
137
+ }
138
+
139
+ ?>
140
+
141
+ ```