views:

47

answers:

2

I have two g:textfields in the first one I should write a number lets say 12 and in the g:textfield next to it it should load the predetermined name for number 12.

The first one is named 'shipper' and the other 'shipperName' Whenever I write the code 12 in the 'shipper' txtfield, it should return the name of the shipper in the 'shipperName' box.

Thanks in advance!

Examples:

If I write the number 12 it should return USPS

And every number should have a different 'shipperName'

Thanks again!

+1  A: 

That's quite easy if you'll use jQuery. Check out the event handlers ("blur" is the one you want which occurs when the user leaves the numerical box).

For example:

$("#shipper").blur(function() { 
    $("#shipperName").load(
        "${createLink(controller: 'shipper', action: 'resolveShipper')}?id=" +
        $("#shipper").val()
    );
});

The $(this).val() at the end is the value of the input field the user just left.

And the "ShipperController.resolveShipper" action would look something like this:

def resolveShipper = {
    render text: Shipper.get(params.id).name, contentType: "text/plain"
}

There are other things you might want to do, like automatically filling in the shipperName field as the user types without leaving the edit field, probably after a delay. However the event handler stays the same, just the event is changing (from "blur" to "change" or something like this)

Matthias Hryniszak
How do I get jQuery working?? Should I download the jQuery plugin??
fgualda87
For this to work you just include it at the top of the page and you should be all set. Look at the jQuery documentation for further information.
Matthias Hryniszak
So I don't need to install jQuery at all?? Just by writing that on top I should be alright?
fgualda87
Where do I declare the certain names of the shippers?? I will update the question with some pictures to make everything clear.
fgualda87
Install the Jquery plugin and check out it's documentation on using it.
Scott Warren
Scott: Exactly right.
Matthias Hryniszak
Ok I think I get it, where should the def resolveShipper go?? In the controller??
fgualda87
Also, the script with the src="jquery" or whatever, how should it be since I installed the jQuery plugin?? Or I don't need it because I installed the plugin??
fgualda87
nvm, I got everything here http://www.grails.org/plugin/jquery
fgualda87
So where do I declare the numbers and names?? :/ I got lost again
fgualda87
A: 

To relate two strings, it's easiest to use an object to create a dictionary/ map, as shown below;

$('#input1').bind('keyup',function() {
     var map = {
         "1":"One",
         "2":"Fish",
         "3":"Bar"
     };

     $('#input2').val(map[$(this).val()]);
});

You can see this in action here: http://www.jsfiddle.net/dCy6f/

If you want the second value only to update when the user has finished typing into the first input field, change "keyup" to "change".

fgualda87