简体   繁体   中英

Get specific element from an object list passed from controller in gsp

I passed a list of objects from controller to the gsp with model as shown below

model: [ houses: houses]

I want to set in jquery that whenever the input value of houseId changed, the input value of houseName will be changed to the name of the specific house based on the houseId. Below is the code:

$( "#houseId" ).change(function() {
    $('#houseName').attr('value', '${houses[0].houseName}');
});`

As you can see, the '0' in houses[0] is suppose to be houseId , but I have no idea how to put houseId inside. Can anyone please enlighten me? Thanks!

A better way to do this is sending the houses list as a JSON array and parsing it with JavaScript.

In your action:

import grails.converters.JSON
....
model: [ houses: houses as JSON]

So you have something like this:

[  
   {  
      "id":1,
      "name":"House 1"
   },
   {  
      "id":2,
      "name":"House 2"
   }
]

In your JS:

var houses = JSON.parse(${houses});
$( "#houseId" ).change(function() {
    var index = $('#houseId').val();
    $('#houseName').attr('value', houses[index].name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM