views:

37

answers:

1

I have two g:select comboboxes that I want to add to the multiple select list when clicking an image.

Here is the function in javascript:

function addToList(list,firstOpt, secOpt)
            {
            var y = document.createElement('option');
            y.text = firstOpt + ' - ' + secOpt;
            y.value = firstOpt+'-'+secOpt;
            var elSel = document.getElementById(list);
            try {
            elSel.add(y, null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
            elSel.add(y); // IE only
            }
            }

I think the problem is here in the actual button:

<img src="${resource(dir:'images',file:'arrow.png')}" onclick="addToList('BList','first','second')"/>

when I click it, "first - second" gets added to the list, not the actual value of the g:select boxes. I also tried ${first} and ${second} but had no luck.

Any help is greatly appreciated, thanks!

+1  A: 

You don't have any code in there that retrieves the values of the first and second select lists.

You would probably need something like this:

function addToList(destinationList, sourceList1Id, sourceList2Id) {

    // your select lists will need ids
    // e.g. <g:select id="listOneId" .../>

    var list1 = document.getElementById(sourceList1Id);
    var list2 = document.getElementById(sourceList2Id);

    var list1value = list1.options[list1.selectedIndex].value;
    var list2value = list2.options[list2.selectedIndex].value;

    // the rest of your addToList() function, replacing 'firstOpt'
    // and 'secondOpt' with 'list1value' and 'list2value' respectively
    // ...
}

You might then use this with the following selects:

<!-- sources -->
<g:select id="fooList" .../>
<g:select id="barList" .../>

<!-- destination -->
<g:select id="bazList" .../>

<img ... onclick="addToList('bazList', 'fooList', 'barList');"/>
Rob Hruska
But I plan on using that function in two or three lists and I don't wanna write 3 different functions for each one, that's why I had those three arguments.
fgualda87
Right - if you look at my last comment on my answer I address that. Let me update my example to better fit your situation.
Rob Hruska
Yeah I got it. I was missing the .value part. Thank you!!
fgualda87
Yep, no problem.
Rob Hruska
Also `"list1.options[list1.selectedIndex].value;"` can be changed to `"list1.value;"` it works too and it can be used with textfields
fgualda87
`list1.value` might not work in some older browsers.
Rob Hruska