Skip to content

Instantly share code, notes, and snippets.

@salsalabs
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salsalabs/a0327c6de6468dcdf37f to your computer and use it in GitHub Desktop.
Save salsalabs/a0327c6de6468dcdf37f to your computer and use it in GitHub Desktop.
Clicks answers in a questionnaire based on queries in the URL.
<script type="text/javascript">
$(document).ready(function () {
// SalsaStaff 88363: Click options in the checkbox/radio button
// questions based on queries passed in the URL. The general form of
// a query is `&Qm=n`, where `m` is the question number and `n` is
// the answer number. Both `m` and `n` are cardinal integers.
//
// @note This GIST contains guard logic to work on a single questoinnaire
// because the script must go into a template.
//
if (/questionnaire_KEY=69/.test(window.location.href)) {
// see http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
function qs(key) {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars[key];
}
var questions = {};
$('.formRow fieldset').each (function(index, value) {
var key = "Q" + (index + 1);
questions[key] = [];
$(this).find('input').each ( function(key2, value2) {
questions[key].push($(this).attr('id'));
})
});
for (key in questions) {
var arg = parseInt(qs(key)) || 0;
if (arg < 1) {
console.log("Error! not a valid number, '" + qs(key) + "', for " + key + ".");
}
else {
var question = questions[key];
if (arg - 1 < question.length) {
var answer = question[arg - 1];
$('#' + answer).click();
console.log("Clicked #" + answer);
}
else {
console.log("Warning! " + key + " does not have an answer " + arg + ".");
}
}
}
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment