Search code examples
javascriptjavahtmlobjectthymeleaf

get undefined when fill input select html with thymeleaf Object in javascript


I am trying to fill input value & text on option select in javascript. The data is get from thymeleaf in html.

here is my source model that i want to store in javascript.

public class JobClassEntity {

  private String jobClassId;
  private String jobTypeId;
  private String jobClassName;

  public JobClassEntity(String jobClassId, String jobTypeId, String jobClassName) {
    this.jobClassId = jobClassId;
    this.jobTypeId = jobTypeId;
    this.jobClassName = jobClassName;
  }
 
  //getter & setter
}

here is my source on controller.

   @GetMapping("/")
   public ModelAndView showCreateNewTml(ModelAndView m, Principal principal){

    User user = (User) ((Authentication) principal).getPrincipal();

    List<JobClassEntity> listJob = jobClassRepository.findAllAssetClass();
    m.addObject("jobclass", listJob);
    m.setViewName("timelines/create-new-timeline");

    return m;
}

listJob is contain 4 data (length listJob = 4). here is my part code page (test.html) where data from controller pass to .js

<script th:inline="javascript">
<![CDATA[*/

    var listJobC = /*[[${jobclass}]]*/ 'default';

>*/
</script>

after it pass to javascript (test.js). i try to fill the data to select option input. here is my source .js.

for(jobc in listJobC)
    {
       var opt = document.createElement("option");
       opt.value= jobc.jobClassId;
       opt.innerHTML = jobc.jobClassName;

       seljob.appendChild(opt);
    }

after i run and test it, the select is show but the value & text is filled with undefined. This is the display of the option value


Solution

  • I don't think for(jobc in listJobC) is doing what you think it is. When I tested that code, it just returned the numbers 0 and 1 which don't have the properties you're looking for... Either use .forEach or a regular for loop.

    for (let i = 0; i < listJobC.length; i++) {
      jobc = listJobC[i];
      
      var opt = document.createElement("option");
      opt.value= jobc['jobClassId'];
      opt.innerHTML = jobc['jobClassName'];
      seljob.appendChild(opt);
    }