开发者

Why doesn't my code work without this alert box?

开发者 https://www.devze.com 2023-04-06 07:32 出处:网络
On one of the edit views of my Grails application I have several chained drop down boxes.When the edit view is called all the values for the object being edited populate correctly, but none of the dro

On one of the edit views of my Grails application I have several chained drop down boxes. When the edit view is called all the values for the object being edited populate correctly, but none of the drop down boxes are populated because they populate via AJAX through jQuery's change function.

To fix this I used the code below, but there is one strange thing. I used an alert box to see what the value was when I was writing the code. With the alert box there everything happens as I expect it to, but as soon as I remove the alert box the line of code tha开发者_Go百科t re-selects the previously cleared value stops working.

<g:javascript>
  $(document).ready(function() {
    cargoDestinationValue = $("#cargoDestination\\.id").val(); //Gets value shown in the selection box. This box is second in the chain.
    $("#account\\.id ").trigger('change'); //Triggers a change.  This box is first in the chain. when a change is detected an AJAX call is made via some other JavaScript and that populates the second selection box in the chain, but doing so clears the selected value.
    alert(cargoDestinationValue); //If this is not here the next line does not seem to be doing what it is supposed to do.
    $("#cargoDestination\\.id").val(cargoDestinationValue); //This re-selects the value that was previously cleared.
  })
</g:javascript>

What is the deal here?


The event that you trigger is queued, so if you don't have the alert, the event is not handled until you exit the function.

Even if you would call the code directly without using an event to trigger it, it has an AJAX call where the response is handled by an event, so that event would be queued.

You should handle the part after the alert in the code that recieves the data from the AJAX call, which of course means that you have to store the selected value somewhere so that the code can get to it.


Could it be that #cargoDestination does not exist at the moment you try to set the value (without the alert box), but will be loaded/inserted while you click "ok" if the alert box is on screen?

I had a similar problem some days ago...

0

精彩评论

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