I’m using grails for a traffic project. It’s my first with grails!
I have a domain Station with two boolean values hasroad and hasrail. In the station controller I use this method:
def hasroadhasrail() {
def station = Station.get(params.stationid)
def response = ['hasroad': station?.hasroad, 'hasrail': station?.hasrail]
render response as JSON
}
Then I have a domain Traffic which is linked to Station with
Station station
with lots of data. If there can’t be road/rails data the input fields are disabled and greyed out.
I’m using jquery 1.8.0
The ajax call in the _form.gsp of traffic looks like this:
<script>
$(document).ready(function(){
// correct for create
$("input.data1").prop('disabled', ${trafficInstance?.station?.hasroad ?: true});
$("input.data2").prop('disabled', ${trafficInstance?.station?.hasrail ?: true});
$("#station").change(function() {
$.ajax({
type: "POST",
url: "${createLink(controller: 'station', action: 'hasroadhasrail')}",
data: { stationid: $(this).val()}
}).done(function( response ) {
if (response.hasroad) {
$("input.data1").prop('disabled', false);
$('input.data1').css('background-color', 'white');
}
else {
$("input.data1").prop('disabled', true);
$('input.data1').css('background-color', 'grey');
}
if (response.hasrail) {
$("input.data2").prop('disabled', false);
$('input.data2').css('background-color', 'white');
}
else {
$("input.data2").prop('disabled', true);
$('input.data2').css('background-color', 'grey');
}
});
});
})
</script>
and here is the dropdown for Stations also in the _form.gsp of traffic
<li class="fieldcontain ${hasErrors(bean: trafficInstance, field: 'station', 'error')} required"> <span class="lbl">Station</span>
<g:select id="station" name="station.id" from="${trafproj.Station.list()}" optionKey="id" required="" value="${trafficInstance?.station?.id}" class="many-to-one" noSelection="['':'-Choose station-']"/>
</li>
When I create new traffic data all works perfectly. I chose a station from the dropdown and if for example hasroad is false for this station the input fields are disabled and greyed out. All above code works great!
Now my problem: If I edit previously created traffic a station is already loaded in the station dropdown. There is no change and therefore the ajax doesn’t work instantly. When I change the station in the dropdown again all works fine.
What do I have to add that the dropdown not only works on change but also when a station was initially loaded?
Put the ajax function into a separate function, instead of an anonymous, inline function.
Then call that function from document.ready() in addition to using it as the onchange handler.
Be sure to change
to