Home > Software engineering >  JQuery generate drop-down list dynamic default selection
JQuery generate drop-down list dynamic default selection

Time:10-20

I am building a DataTable and everything renders perfectly fine.

one of the columns, I need to render a select/drop-down list and set default selected value.

I managed to render

render: function (data) {  
  //e.g. data.selectedvalue = 1 or 2 or 3
        
 var select = $("<select class='target' id='empstatus'><option value ='1'>Open</option><option value ='2'>Close</option><option value ='3'>N/A</option></select>");

 //tried to set value - but it is not setting default selection, always shows the first selection after it renders
 select.val(data.selectedvalue).attr('selected', 'selected');


 return select.prop("outerHTML");
}                              

This list renders, my question how can I set dynamic selected value?

CodePudding user response:

You need to set the attribute of the appropriaet option, not the dropdown, so that it will be included in the outerHTML.

render: function (data) {  
  //e.g. data.selectedvalue = 1 or 2 or 3
        
  var select = $("<select class='target' id='empstatus'><option value ='1'>Open</option><option value ='2'>Close</option><option value ='3'>N/A</option></select>");
  select.find(`option[value=${data.selectedvalue}]`).attr('selected', 'selected');

 return select.prop("outerHTML");
}    
  • Related