views:

125

answers:

1

How do you set the selectedIndex on a <g:select> tag with a value from the list? I have a page that allows you to add a record. the page then goes to a view containing a g:select and i want the g:select to default to that item i just inserted into the database.

I tried passing the new object in the flash but i can't figure out how to get it's index in the list being used to generate the g:select data.

+1  A: 

Supposing you store a Book object in flash.book at the controller level, your second page could look like this :

<html>
    <head>
        <g:javascript library="prototype" />
        <g:javascript>
              function showLast(selectedId) {
                  if (selectedId) {
                    $$('#books option[value=' + selectedId + "]")[0].selected = true;
                  } else {
                    $('books').selectedIndex = 0;
                  }
              };

              Event.observe(window, 'load', init, false);

              function init() {
                  showLast(${flash?.book?.id});
              }
            </g:javascript>
    </head>
    <body>
        <g:select id="books" name="id"
                  from="${Book.list()}"
                  value="title"
                  optionValue="title"
                  optionKey="id"
         />
    </body>
</html>
Philippe
Awesome works perfectly, I adapted it to jQuery with $('#fileSelect').val(${flash?.upload?.id});
TripWired
Cool. I just thought of something : you will loose your selection if you refresh the page because of the flash scope. Maybie it would be better to store the value in a hidden field the first time you enter the page and read it from there on subsequent page refreshes...
Philippe