JS window.location issue - javascript

I use this code for a redirection form when selecting a different jersey from the select input but while the JSfiddle works at my site there is no redirection from the window.location command.
https://jsfiddle.net/giorgoskey/95k1tc0b/4/
function populateSecondTextBox() {
var p = document.getElementById('your_name');
var txt = document.getElementById('txtFirst');
p.textContent = txt.value;
}
function populateNumberTextBox() {
var p = document.getElementById('your_number');
var txt = document.getElementById('txtSecond');
p.textContent = txt.value;
}
var goBtn = document.getElementById("goBtn");
var shirts = document.getElementById("shirts");
goBtn.onclick = function() {
window.location = shirts.value;
}

Hou have to use history.pusthState()
MDM
history.pushState(state, title [, url])
empty state and title.
window.history.pushState({}, '', url);
in your case
var goBtn = document.getElementById("goBtn");
var shirts = document.getElementById("shirts");
goBtn.onclick = function() {
window.history.pushState({}, '', shirts.value);
}

Related

searchParams.get returning "Null" when values are present

I'm trying to grab URL params from a page link to prepopulate a form in an iFrame, but am struggling with the params returning 'null' and need some guidance. So far, the script appears to work by populating the form with "null", however, it is unsuccessfully populating params that have valid values in my URL. The javascript below 'f.src' is scripting provided by my forms service.
(I apologize for the ugly console.logs, but am using those for troubleshooting.)
[Console Preview][1]
***UPDATE: With my updated code, per user suggestion, I updated my .get statements to specify the param with a string, but it's still returning 'null'.
try{
var endpoint = "https://forms.myformsite.com/";
console.log(endpoint);
var url_string = "https://my.site.com/landingpage?fname=Jeff&lname=Bezos&email=jeff#amazon.com&company=Amazon&title=Founder"; /*window.location.href;*/
console.log(url_string);
var url = new URL(url_string);
console.log(url_string);
var fname = url.searchParams.get('fname');
console.log(fname);
var lname = url.searchParams.get('lname');
console.log(lname);
var email = url.searchParams.get('email');
console.log(email);
var company = url.searchParams.get('company');
console.log(company);
var title = url.searchParams.get('title');
console.log(title);
var formURL = endpoint+"&fname="+fname+"&lname="+lname+"&email="+email+"&company"+company+"&title="+title;
console.log(formURL);
var f = document.createElement("iframe");
f.src = formURL;
console.log(f.src);
f.style.border = "none";
f.style.height = "878px";
f.style.width = "90%";
f.style.transition = "all 0.5s ease";
var d = document.getElementById("divFormID");
d.appendChild(f);
window.addEventListener('message', function() {
var evntData = event.data;
if (evntData && evntData.constructor == String) {
var zf_ifrm_data = evntData.split("|");
if (zf_ifrm_data.length == 2) {
var zf_perma = zf_ifrm_data[0];
var zf_ifrm_ht_nw = (parseInt(zf_ifrm_data[2], 10) + 15) + "px";
var iframe = document.getElementById("divFormID").getElementsByTagName("iframe")[0];
if ((iframe.src).indexOf('formperma') > 0 && (iframe.src).indexOf(zf_perma) > 0) {
var prevIframeHeight = iframe.style.height;
if (prevIframeHeight != zf_ifrm_ht_nw) {
iframe.style.height = zf_ifrm_ht_nw;
}
}
}
}
}, false);
} catch (e) {}
})();```
[1]: https://i.stack.imgur.com/z75q0.png
[2]: https://i.stack.imgur.com/bjqoP.png
For all .get() calls, you're passing in an (undefined) variable instead of a string:
var fname = url.searchParams.get(fname);
This should be:
var fname = url.searchParams.get('fname');

How add a filter in server script with query

i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");

Issues with google

Is it possible, depending on the environment of the company, that some features of Google are non-existent? I tried some functions with my personal email and it works; but, in a professional environment it doesn't work.
function getDataForSearch() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("PEP FORMULAR");
return ws.getRange(6, 1, ws.getLastRow()-1, 6).getValues();
}
var data;
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchInput = document.getElementById("searchInput").value.toString().toLowerCase().trim();
var searchWords = searchInput.split(/\s+/);
//var searchColumns = [0,1,2,3,4,5];
var searchColumns = [0];
//and
var resultsArray = searchInput == "" ? [] : data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) != -1;
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var typeInitiativeColumn = tr.querySelector(".type-initiative");
var pepRefColumn = tr.querySelector(".pep-ref");
var projectNameColumn = tr.querySelector(".project-name");
pepRefColumn.textContent = r[0];
typeInitiativeColumn.textContent = r[2];
projectNameColumn.textContent = r[5];
searchResultsBox.appendChild(tr);
});
}
This code works but, when I try to reproduce it in a professional environment, the function setDataForSerach() is not able to get the data from the function getDataForSearch() and make a copy.

Guardian API Search Javascript JSONP

I have a html page which I can type in a topic to search into a text box called "search", and there is a submit button called "searchbutton". I trying to search the guardian API and then load the results onto the html page in the "content" div, however, I have no idea where I am going wrong and would appreciate some help. I don't need an API key as I am using the public version. Thanks,
var baseURL = "http://content.guardianapis.com/search";
var searchQuery;
function init() {
var search = document.getElementById("search");
var searchButton = document.getElementById("searchbutton");
searchButton.onclick = getSearchValue;
}
function getSearchValue () {
var search = document.getElementById("search");
var searchResult = search.value;
searchQuery = searchResult.replace(" ", "+");
loadSearch();
}
function loadSearch() {
makeJSONPCall(searchQuery, "loadSearchCallBack");
}
function makeJSONPCall(queryPart, callback) {
var url = baseURL + "?q=";
url = url + queryPart;
url = url + "&callback=" + callback;
var scriptElement = document.createElement("script");
scriptElement.id = "jsonp";
scriptElement.src = url;
document.head.appendChild(scriptElement);
}
function loadSearchCallBack(data){
cleanupScript();
listResults(data);
}
function listResults(data) {
for ( var i=0; i< data.response.results.length; i++) {
var list = data.response[i];
renderResults(i, data.response[i]);
}
}
function renderResults(i, list) {
var resultDiv = document.getElementById("content");
resultDiv.innerHTML = list.results[i].webTitle;
}
function cleanupScript() {
var scriptElement = document.getElementById("jsonp");
scriptElement.parentNode.removeChild(scriptElement);
}
window.onload = init;
I wound up making a jsfiddle, including several changes.
JavaScript:
var baseURL = "http://content.guardianapis.com/search";
var searchQuery;
function init() {
var search = document.getElementById("search");
var searchButton = document.getElementById("searchbutton");
searchButton.onclick = getSearchValue;
}
function getSearchValue() {
var search = document.getElementById("search");
var searchResult = search.value;
searchQuery = searchResult.replace(" ", "+");
loadSearch();
}
function loadSearch() {
makeJSONPCall(searchQuery, "loadSearchCallBack");
}
function makeJSONPCall(queryPart, callback) {
var url = baseURL + "?q=";
url = url + queryPart;
url = url + "&callback=" + callback;
var scriptElement = document.createElement("script");
scriptElement.id = "jsonp";
scriptElement.src = url;
document.head.appendChild(scriptElement);
}
function loadSearchCallBack(data) {
listResults(data);
cleanupScript();
}
function listResults(data) {
for (var i = 0; i < data.response.results.length; i++) {
var list = renderResults(data.response.results[i]);
}
}
function renderResults(result) {
var resultDiv = document.getElementById("content");
resultDiv.innerHTML += result.webTitle;
}
function cleanupScript() {
var scriptElement = document.getElementById("jsonp");
scriptElement.parentNode.removeChild(scriptElement);
}
init();
Html:
<input id="search" type="search" />
<button id="searchbutton">Search</button>
<div id="content"></div>

JQuery with several Elements issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}

Categories