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>
Related
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);
}
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.
It's used in some site.. to hide iframe src url
String.prototype.edoceD = function () {
var x = this.length;
var edoceD = "";
while (x>=0) {
edoceD = edoceD + this.charAt(x);
x--;
}
return edoceD;
}
var OLID = 'a66793a78396b6d6a6d6c6b61746'
OLID = OLID.edoceD()
Result of this OLID ?
I have a script in HTML page head that declares a function to make a get requests for JSON data and passes it to element’s innerHTML.
function called on page load.
Script in head correctly gets JSON data and populates elements innerHTML.
I would like to cross-fade loop between the 2 bits of JSON data.
Script in body tries to get element’s innerHTML and create array to use as input to cross fade loop.
Element’s innerHTML variable comes back empty.
The cross-fade loop script works if strings are declared in array.
Fiddle here
How can I get the JSON values into the text cycle?
<script>
var intervalID = window.setInterval(insertText, 2000);
function insertText(){
const Http = new XMLHttpRequest();
const url = "https://api.kraken.com/0/public/Ticker?pair=XXBTZUSD";
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
const price = Http.responseText
const priceJson = JSON.parse(price);
var priceJsonBtc = priceJson.result.XXBTZUSD.c[0];
var btc = parseFloat(priceJsonBtc)
var btcp = btc.toFixed(2)
console.log(btcp);
document.getElementById("priceUsd").innerHTML = "$" + btcp + " USD";
const usdp = btcp
}
const HttpGbp = new XMLHttpRequest();
const urlGbp = "https://api.kraken.com/0/public/Ticker?pair=XXBTZGBP";
HttpGbp.open("GET", urlGbp);
HttpGbp.send();
HttpGbp.onreadystatechange=(e)=>{
const priceGbp = HttpGbp.responseText
const priceJsonGbp = JSON.parse(priceGbp);
var priceJsonBtcGbp = priceJsonGbp.result.XXBTZGBP.c[0];
var btcGbp = parseFloat(priceJsonBtcGbp)
var btcpGbp = btcGbp.toFixed(2)
console.log(btcpGbp);
document.getElementById("priceGbp").innerHTML = "£" + btcpGbp + " GBP";
const gbpp = btcpGbp
}
}
</script>
</head>
<body onload=insertText()>
<h1 id="priceUsd"></h1>
<h1 id="priceGbp"></h1>
<h1 id="changer">£ GBP</h1>
<script>
var usd = document.getElementById("priceUsd").innerHTML;
var gbp = document.getElementById("priceGbp").innerHTML;
/* This does not work */
/* var words = [usd, gbp]; */
/* This does work */
var words = ["£ GBP", "$ USD"];
var i = 0;
var text = "BTC";
function _getChangedText() {
i = (i + 1) % words.length;
return text.replace(/BTC/, words[i]);
}
function _changeText() {
var txt = _getChangedText();
var d = document.getElementById("changer")
d.className = "fadeOut";
setTimeout(function(){
d.className = "";
document.getElementById("changer").innerHTML = txt;
}, 900);
}
setInterval("_changeText()", 1000);
</script>
</body>
Resolved with setInterval to delay pulling HTML elements before they had been updated:
var intervalID = window.setInterval(updateText, 1500);
function updateText() {
var usd = document.getElementById("price").innerHTML
var gbp = document.getElementById("priceGbp").innerHTML
words = [usd, gbp]
}
var i = 0;
var text = "BTC";
function _getChangedText() {
i = (i + 1) % words.length;
return text.replace(/BTC/, words[i]);
}
function _changeText() {
var txt = _getChangedText();
var d = document.getElementById("changer")
d.className = "fadeOut";
setTimeout(function(){
d.className = "";
document.getElementById("changer").innerHTML = txt;
}, 800);
}setInterval("_changeText()", 3000)
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
}