Reputation: 1281
I currently have this...
var phpArray = <?php echo json_encode($tourdistance['tourdistance']); ?>;
$('#tour').on('change', function (event) {
$('#distance').val(phpArray[$(this).val()]);
});
...updating an input element 'distance' when a drop down 'tour' is changed. When the form is submitted, with validation errors, I have the HTML/PHP set up so that it remembers the users choice for that field. However, the above is not triggered unless they re-select that drop down element. Which is a poor user experience because visually it will look correctly selected.
How can I also have it update on page-load, or otherwise setup so that 'distance' stays updated, even after a page load?
Here is the page...
http://antipodecycling.com/donate-support/sponsor-us/
Current solution:
var phpArray = <?php echo json_encode($tourdistance['tourdistance']); ?>;
$(document).ready(function(){
function updateSelect(){
var selectInput = $("#tour");
var distance = phpArray[selectInput.val()];
$('#distance').val(distance);
}
updateSelect();
function updatePledge(){
var pledge = "<?php echo set_value('pledge'); ?>";
$('#pledge').val(pledge);
}
updatePledge();
$("#tour").on('change', function(){
updateSelect();
});
});
Upvotes: 0
Views: 64
Reputation: 5424
abstract the update function, and then call on two different events: document ready and select change.
$(document).ready(function(){
function updateSelect(){
alert('update select fired');
var selectInput = $("#tour");
var distance = phpArray[selectInput.val()];
alert(distance);
$('#distance').val(distance);
$('#pledgedistance').html(distance);
}
updateSelect();
$("#tour").on('change', function(){
updateSelect();
});
});
Upvotes: 1