开发者

How do you update a TextField from a grails remoteLink?

开发者 https://www.devze.com 2022-12-23 02:50 出处:网络
Existing markup: <g:textField name=\"identifier\"/> <g:remoteLink action=\"newId\" update=\"identifier\">generate new id</g:re开发者_高级运维moteLink>

Existing markup:

<g:textField name="identifier"/>
<g:remoteLink action="newId" update="identifier">generate new id</g:re开发者_高级运维moteLink>

Corresponding HTML markup:

<input type="text" id="identifier" name="identifier">
<a onclick="new Ajax.Updater('guid','/webapp/domain/newId',{asynchronous:true,evalScripts:true});return false;" href="/webapp/domain/newId">generate</a>

The HTML markup it generates when the link is clicked:

<input type="text" id="identifier" name="identifier">THE-NEW-ID-HERE</input>
<a onclick="new Ajax.Updater('guid','/webapp/domain/newId',{asynchronous:true,evalScripts:true});return false;" href="/webapp/domain/newId">generate</a>


Try

<div id="updatableArea">
  <g:textField name="identifier"/>
</div>
<g:remoteLink action="newId" update="updatableArea">generate new id</g:remoteLink>

In your controller return the HTML fragment

render(text:"<input type='text' id='identifier' name='identifier'>${newid}</input>", contentType:'text/html')

The remoteLink will simply update the contents of the node so it won't update the "value" of the textfield.

Hope that helps.


Another way using the onSuccess event:

def getName = {
   def exchange = Exchange.findById(params.id)
   if (!exchange) {
      render 'not found'
   }
   else {
      render(builder: "json") {
         exchange
      }
   }
}
...
<script>
   function fillName(e) {
      var obj = toJson(e);
      $('name').value = obj.name;
   }

   function toJson(obj) {
      return eval('(' + e.responseText + ')');
   }
</script>
...
<g:remoteLink action="getName" id="1" onSuccess="fillName(e)">
   Get
</g:remoteLink>
<input type='text' name='name' id='name'/>


just add the following to the remoteLink:

onSuccess="\$('identifier').value=e.responseText;"

So the final result (which works perfectly):

<g:textField name="identifier"/>
<g:remoteLink action="newId" onSuccess="\$('identifier').value=e.responseText;">generate new id</g:remoteLink>

2 things to note:

  1. the $ must be escaped due to the 'grails' processing of that attribute.
  2. I'm using the Prototype javascript library. Other libraries may different syntax, but the basic idea is the same.
0

精彩评论

暂无评论...
验证码 换一张
取 消