Skip to content

Instantly share code, notes, and snippets.

@wecsam
Created June 8, 2019 20:12
Show Gist options
  • Save wecsam/f2a3151ec804d16f5356fe81befe4582 to your computer and use it in GitHub Desktop.
Save wecsam/f2a3151ec804d16f5356fe81befe4582 to your computer and use it in GitHub Desktop.
This script makes the origin and destination fields on the NJ Transit train schedule page persistent.
// ==UserScript==
// @name NJ Transit Train Schedule Station Persister
// @namespace https://www.wecsam.com/
// @version 0.1
// @description This script fills the origin and destination fields with the last values that you entered.
// @author You
// @match https://www.njtransit.com/sf/sf_servlet.srv?hdnPageAction=TrainTo
// @match https://www.njtransit.com/sf/sf_servlet.srv?hdnPageAction=TrainTo#
// @grant none
// ==/UserScript==
(function() {
'use strict';
var elForm = document["frm_tr_schedules"],
elSelOrigin = elForm["selOrigin"],
elSelDestination = elForm["selDestination"],
/**
* This function finds the <option> element inside the given <select>
* element that matches the given value and then selects that <option>.
*
* @return true if a matching <option> was found, false otherwise
*/
setSelectElementValue = function(elSelect, value){
var i;
for(i = 0; i < elSelect.children.length; ++i){
if(elSelect.children[i].value == value){
elSelect.children[i].selected = true;
return true;
}
}
return false;
},
makeSelectElementPersistent = function(elSelect, localStorageKey){
// First, load the last value.
if(localStorage.hasOwnProperty(localStorageKey)){
setSelectElementValue(elSelect, localStorage[localStorageKey]);
}
// Add an event listener to save changes.
elSelect.addEventListener("change", function(event){
localStorage[localStorageKey] = elSelect.value;
});
};
// Make the <select> elements persistent.
makeSelectElementPersistent(elSelOrigin, "trainToSelOrigin");
makeSelectElementPersistent(elSelDestination, "trainToSelDestination");
// Add a reverse button.
var elBtnReverse = document.createElement("input");
elBtnReverse.type = "button";
elBtnReverse.value = "Reverse Trip";
elBtnReverse.addEventListener("click", function(event){
var old = elSelOrigin.value;
setSelectElementValue(elSelOrigin, elSelDestination.value);
setSelectElementValue(elSelDestination, old);
});
elForm.querySelector("input[type=submit]").parentElement.appendChild(
elBtnReverse
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment