Ajax(jQuery)でselectタグを書き換える
jQueryでAjaxリクエストの結果でselectタグを書き換えるときの書き方
数年ぶりに書いたら完全に忘れていたので備忘録として記事にする。
buttonをクリックした時に、selectタグを書き換える。
以下htmlのコード
<button id="trigger">button</button> <div id="targetContainer"> <select id="target"> <option>default</option> </select> </div>
以下javascriptのコード
正確には覚えていないが、optionのみの書き換えだと何らかの問題があり、
場当たり的にselectタグごと書き換えにした。
何故だったんだろうか。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(function(){ $("#trigger").on("click", function(){ $.ajax({ type: 'get', datatype: 'json', contentType: 'application/json', url: 'url', data: { "id" : 1 } }) // 成功時処理 .done(function(data){ var selectHtml = "<select id='target'>"; $.each(data, function (i) { selectHtml += "<option value='" +data[i].id + "'>" + data[i].value + "</option>"; }); selectHtml += "</select>"; $("#targetContainer").html(selectHtml); }) // 失敗時処理 .fail( function(xhr, textStatus, errorThrown) { alert(xhr.responseText); }); }); }) </script>