●test.js
console.log(document.getElementById('select_test_info')); document.getElementById('select_test_info').addEventListener('change', function(event) { //thisもevent.targetもセレクトボックス要素です console.log(this, event.target, event); var option = this.options[this.selectedIndex]; document.querySelector('input[name^="test_d_name"]').value = option.dataset.disp; document.querySelector('input[name^="test_d_address"]').value = option.dataset.address; }, false);
●test.tpl
<script language="JavaScript" src="test.js?t={$smarty.now}"></script> ・ ・ ・ <h3 class="Test_header">テスト</h3> <table data-role="table" id="test_tab" data-mode="reflow" class="ui-responsive table-stroke"> <thead> <tr> <th width="30%">名前</th> <th width="30%">名</th> <th width="30%">住所</th> <th width="10%">削除</th> </tr> </thead> <tbody id="test_tbody"> {assign var='i' value=0} <tr> <td> <select name="test_info" id="select_test_info" data-native-menu="true"> <option value="">選択してください</option> {section name=idx loop=$test_list} <option value="{$test_list[idx].test_name|escape:"html"}"{if $test_list[idx].test_name == $test_list} selected{/if} data-disp="{$test_list[idx].test_d_name}" data-address="{$test_list[idx].test_address}">{$test_list[idx].test_name}</option> {/section} </select> </td> <td><input type="text" name="test_d_name[{$i}]" value="{$test_list[idx1].test_d_name|escape:"html"}" placeholder="名" /></td> <td><input type="text" name="test_address[{$i}]" value="{$test_list[idx1].test_address|escape:"html"}" placeholder="住所" /></td> <td><button type="button" id="btn_del_test{$i}" class="deleteTest ui-btn ui-shadow ui-corner-all ui-btn-icon-left ui-icon-delete">削除</button> </tr> </tbody> </table>
「test.tpl」から「test.js」を読み込ませて処理をしようとしています。
「選択してください」ラベルから選んだ「$test_list[idx].test_name」から同じ配列インデックスの「test_d_name」と「test_address」の値を
テキストボックスに表示したく考えております。上記は自分なりに考えてものです。
こちらを実施すると、開発者ツール上にて
「Uncaught TypeError: Cannot read property 'addEventListener' of null」
と表示され、テキストボックスに値が反映されません。
console.log(document.getElementById('select_test_info'));
の値はnullとなってしまってます。
「選択してください」ラベルには「test_name」の値を選択できる状態になっております。
データ構造は
array(2) { [0]=> array(3) { ["test_name"]=> string(15) "テスト太郎" ["test_d_name"]=> string(6) "太郎" ["test_address"]=> string(6) "東京" } [1]=> array(3) { ["test_name"]=> string(15) "テスト花子" ["test_d_name"]=> string(6) "花子" ["test_address"]=> string(6) "大阪" } }
となっております。
どのようにしたら値がセットできるかご教授いただきたく思います。
宜しくお願いします。
回答2件
あなたの回答
tips
プレビュー