質問編集履歴

1

具体的なコードを追加

2017/10/04 05:51

投稿

garamond
garamond

スコア150

test CHANGED
File without changes
test CHANGED
@@ -2,17 +2,57 @@
2
2
 
3
3
  jQuery で $('input[name=prefecture]').on('change') などとしてもダメです。
4
4
 
5
+ ```HTML
6
+
7
+ <form class="h-adr">
8
+
9
+ <span class="p-country-name" style="display:none;">Japan</span>
10
+
11
+ <input type="text" name="zip" class="p-postal-code">
12
+
13
+ <input type="text" name="prefecture" class="p-region">
14
+
15
+ <input type="text" name="city" class="p-locality">
16
+
17
+ <input type="text" name="address" class="p-street-address p-extended-address">
18
+
19
+ <input type="text" name="city_code">
20
+
21
+ </form>
22
+
23
+ ```
24
+
5
25
  ```JavaScript
6
26
 
7
- $('input[name=zip]').on('keypress keyup', function(){
27
+ $(function(){
8
28
 
9
- // input[name=zip] には class="p-postal-code" してあります
29
+ $('input[name=zip]').on('keyup', function(){
10
30
 
11
- if ($('input[name=prefecture]').val()) {
31
+ // $('input[name=city]').on('change', function(){ が理想
12
32
 
13
- // 拾えない!
33
+ if ($('input[name=city]').val()) {
14
34
 
35
+ // 取得した瞬間には反応しない
36
+
37
+ $.post('/get/city/code', { // 市区町村コードを取得するPHPプログラム呼び出し
38
+
39
+ prefecture: $('input[name=prefecture]').val(),
40
+
41
+ city: $('input[name=city]').val()
42
+
43
+ }, 'json').done(function(r){
44
+
45
+ $('input[name=city_code]').val(r.code);
46
+
47
+ }).fail(function(){
48
+
49
+ alert('取得失敗');
50
+
51
+ });
52
+
15
- }
53
+ }
54
+
55
+ });
16
56
 
17
57
  });
18
58