wawan Setiyawan wawan Setiyawan - 3 months ago 7
jQuery Question

Create element select-option and selected value

I am trying the code given below :



var tmp1 = "3";
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'>Proses</option><option value='1'>Return</option><option value='2' >Selesai</option></select>";

$('select.status_detail_hanca').val(tmp1);
$(".tbody_detail_hanca_checking").append(status_detail_hanca);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>

</div>





but this code is not working,
tmp1
value from json and this
select-option
in loop
$.each
.I am trying this code also :



var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'"+ if(tmp1 === '0'){$(this).append("selected")} +">Proses</option><option value='1'"+ if(tmp1 === '0'){$(this).append("selected")} +">Return</option><option value='2'"+ if(tmp1 === '0'){$(this).append("selected")} +">Selesai</option></select>";





but, its also not working.
How to solve this problem ?

Thanks guys !

Answer

You can try something like this. Also Its better to use loop and create a string than hard-coding it

var tmp1 = "3";
var optionList = ["Proses", "Return","Selesai", "TEST", "FOO"]
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' >";

status_detail_hanca = optionList.reduce(function(p, c, i){
  var _t = "<option value='"+i+"' ";
  if(tmp1 == i){
    _t += "selected='selected'";
  }
  _t += ">" + c + "</option>";
  p += _t;
  return p;
}, status_detail_hanca);
status_detail_hanca += "</select>";
$(".tbody_detail_hanca_checking").append(status_detail_hanca);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>

</div>