This script will apply autocomplete to the first sub-question of a multiple-short-text question and add a button to the third sub-question that will get the GPS coordinates (if allowed).
Both the autocomplete function and the getGPS() function will load the second sub-question with GPS coordinates formatted for use as the default location for the map.
Code:
<link href="/upload/surveys/{SID}/files/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="/upload/surveys/{SID}/files/jquery-ui.min.js"></script>
<script src="/upload/surveys/{SID}/files/jquery.csv.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).on('ready pjax:complete',function() {
// Identify this question
var thisQuestion = $('#question{QID}');
var url = "/upload/surveys/{SID}/files/NAMES_cleaned.csv";
// Hide the second input
$('.question-item:eq(1)', thisQuestion).hide();
var Names = [];
var Coords = { };
$.get(url, function(data){
fullArray = $.csv.toArrays(data);
$(fullArray).each(function(i, item){
Names.push(item[0]);
Coords[item[0].toLowerCase()] = item[1];
});
// Initiate the Autocomplete plugin
$('input[type=text]:eq(0)', thisQuestion).autocomplete({
minLength: 2,
source: Names,
select: function(event, ui) {
$('input[type=text]:eq(1)', thisQuestion).val(Coords[ui.item.value.toLowerCase()].replace(/;/, ' ')).trigger('keyup');
$('input[type=text]:eq(2)', thisQuestion).val('').trigger('keyup');
}
}).on('change', function(e) {
$('input[type=text]:eq(1)', thisQuestion).val(Coords[$.trim($(this).val()).toLowerCase()].replace(/;/, ' ')).trigger('keyup');
$('input[type=text]:eq(2)', thisQuestion).val('').trigger('keyup');
});
});
// Insert the GPS button
$('input[type=text]:eq(2)', thisQuestion).before('<button type="button" class="btn btn-primary gps-button" style="margin-bottom: 5px;">Get GPS Coordinates</button>');
// Get GPS coordinates
$('.gps-button', thisQuestion).on('click', function(e) {
getGPS();
});
function getGPS() {
disableButtons();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showGPS, gpsError);
} else {
$('input[type=text]:eq(2)', thisQuestion).val('No GPS Functionality');
enableButtons();
}
}
function gpsError(error) {
alert('GPS Error: '+error.code+', '+error.message);
enableButtons();
}
function showGPS(position) {
$('input[type=text]:eq(0)', thisQuestion).val('').trigger('keyup');
$('input[type=text]:eq(1)', thisQuestion).val(position.coords.latitude+' '+position.coords.longitude).trigger('keyup');
$('input[type=text]:eq(2)', thisQuestion).val(position.coords.latitude+';'+position.coords.longitude).trigger('keyup');
enableButtons();
}
function disableButtons() {
$('#ls-button-submit').prop('disabled', true);
$('.gps-button', thisQuestion).prop('disabled', true);
}
function enableButtons() {
$('#ls-button-submit').prop('disabled', false);
$('.gps-button', thisQuestion).prop('disabled', false);
}
});
</script>