How to dynamically append data to a webpage after API call? - javascript

I am trying to create a webpage that, given a user input, returns a list of results from wikipedia. I have gotten the call to Wikipedia's API to work fine, but when I attempt to append the data to my webpage, it flickers on for a split second and then disappears. I suspect it has to do with the event handlers, but I have tried several alternatives without luck. I also looked around SO and the web at large but could not find a solution. Here is my code:
var results = [];
$("#search").on("keydown", "#searchinput", function(event) {
if (event.key === "Enter") {
var searchParameter = encodeURIComponent(this.value);
var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";
$.getJSON(link, function(data) {
for (var key in data) {
results.push(data[key]);
}
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].length; j++) {
$("#results").append(results[i][j]);
}
}
})
}
});
Thanks in advance for any assistance you can provide! I am happy to provide more information if necessary.

The call to $.getJSON should be in the if block with the variable assignments.
var results = [];
$("#search").on("keydown", "#searchinput", function(event) {
if (event.key === "Enter") {
var searchParameter = encodeURIComponent(this.value);
var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";
$.getJSON(link, function(data) {
for (var key in data) {
results.push(data[key]);
}
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].length; j++) {
$("#results").append(results[i][j]);
}
}
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="search">
<input id="searchinput" type="text">
</div>
<div id="results">
</div>

Related

localstorage is not working after window.location.href

I am setting a value checked using localstorage.setitem and using window.location.href to redirect to another page. When page loads and I am trying to acess the saved value using localstorage.getitem, it is not working.
Here is my code:
<input type="checkbox" name="names" onchange="submit(this)" />
function submit(element) {
var names = document.getElementsByName('names');
var selectedList = [];
for (var i = 0; i < names.length; i++) {
if (names[i].checked == true) {
window.localStorage.setItem(names[i].checked, "checked");
}
}
window.location.href = "/testpage.html";
}
$(document).ready(function () {
var names = document.getElementsByName('names');
for (var i = 0; i < names.length; i++) {
if (window.localStorage.getItem(names[i].checked) == "checked") {
names[i].setAttribute('checked', 'checked');
}
}
})
Let's say you're on page x.html and you're redirecting to another page from this page using this line
window.location.href = "/testpage.html";
So any code written in javascript of x.html after the redirecting will not execute, because the execution context of JS now moves to javascript written for testpage.html.
With that said, the solution to your problem will be, to set the localStorage from x.html's JS and when redirected to testpage.html the handle the getting from localStorage part there and then set the values gotten fro localStorage to the checkboxes.
Let's see example of what i've explained above.
Your x.html should look something like this:
function submit(element) {
var names = document.getElementsByName('names');
var selectedList = [];
for (var i = 0; i < names.length; i++) {
if (names[i].checked == true) {
window.localStorage.setItem(names[i].checked, "checked");
}
}
window.location.href = "/testpage.html";
}
<input type="checkbox" name="names" onchange="submit(this)" />
And javascript for testpage.html should look something like this:
$(document).ready(function () {
var names = document.getElementsByName('names');
for (var i = 0; i < names.length; i++) {
if (window.localStorage.getItem(names[i].checked) == "checked") {
names[i].setAttribute('checked', 'checked');
}
}
})

Inline Javascript in Wordpress

I'm have multiple tables and have an option dropdown that loops through them. When I tested the code in http://codepen.io/fernandob/pen/JEJRMW , it all works fine but when adding it in my Wordpress page, it doesn't run. In wordpress i'm using visual composer and in a text block, via the text editor i paste the html code, following this.
<script>
if (typeof suffixes !== "undefined") {
suffixes += ",1390152632";
} else {
suffixes = "1390152632";
}
function changeCurrency_1390152632() {
var idx = document.getElementById("id_selected_currency_1390152632").options.selectedIndex;
var currency = document.getElementById("id_selected_currency_1390152632").options[document.getElementById("id_selected_currency_1390152632").options.selectedIndex].value;
var currencies = ["EUR", "USD", "GBP"];
var i, j;
for (i = 0; i < 3; i++) {
var els = document.getElementsByClassName("currency_" + currencies[i]);
var cnt = els.length;
if (currency == currencies[i]) {
for (j = 0; j < cnt; j++) {
els[j].style.display = "block";
}
var a = suffixes.split(",");
for (j = 0; j < a.length; j++) {
document.getElementById("id_selected_currency_" + a[j]).options.selectedIndex = idx;
}
} else {
for (j = 0; j < cnt; j++) {
els[j].style.display = "none";
}
}
}
}
</script>
It's replace with html code because you are using text block.
Use RawHTML and RawJS elements under the structure tab using visual composer.
HTML code paste in the Raw HTML element and JavaScrip code paste in the Raw JS element.
See also image:
Hope this answer help you.

Count occurrences of string in array one against array two [duplicate]

This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have two arrays of zip codes. The first array has many zip codes including duplicates. The second array has the duplicates removed to show only the unique zip codes.
How can I check how many times each unique zip code appears in the zip code containing duplicates?
For example, if I have two values for 21218, how can I check that there are two values? I would like to iterate through the unique name array if possible to check against the duplicate name array.
Edit: This question is similar to this previously asked question here. However, it differs because the goal is to use the existing code and incorporate it into the solution.
var url = 'https://data.baltimorecity.gov/resource/uds6-qsb6.json?$limit=50000';
var manyZipArray = [];
var zipArray = [];
$(document).ready(function() {
$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i++) {
manyZipArray.push(data[i].zip);
};
$.each(manyZipArray, function(i, el) {
if ($.inArray(el, zipArray) === -1) zipArray.push(el);
});
zipArray.sort();
for (var i = 0; i < zipArray.length; i++) {
$('#myList').append("<li>" + zipArray[i] + "</li>");
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 style="text-align: center" ;>Unique Zip Codes </h3>
<ul id="myList"></ul>
You can use a javascript object to store the number of occurences of each zip code by setting a new key of the object using the zip code.
See code below:
var url = 'https://data.baltimorecity.gov/resource/uds6-qsb6.json?$limit=50000';
var manyZipArray = [];
var zipArray = [];
var numberOfZips = {};//object to hold the counters
$(document).ready(function() {
$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i++) {
manyZipArray.push(data[i].zip);
if (data[i].zip in numberOfZips){
numberOfZips[data[i].zip] += 1;
}else{
numberOfZips[data[i].zip] = 1;
}
};
$.each(manyZipArray, function(i, el) {
if ($.inArray(el, zipArray) === -1) zipArray.push(el);
});
zipArray.sort();
for (var i = 0; i < zipArray.length; i++) {
$('#myList').append("<li>" + zipArray[i] +","+numberOfZips[zipArray[i]]+ "</li>");
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 style="text-align: center" ;>Unique Zip Codes </h3>
<ul id="myList"></ul>
I would do a loop that iterates the non-duplicate array, and for each zip value, iterate the full array and count it's appearances. In my example code below I store the values in a new array, but you can do whatever you need with them.
var zipOcurrences = array();
var i = 0;
zipArray.each(function(){
zipOcurrences[i] = 0;
var zip = $(this);
manyZipArray.each(function(){
if ($(this)==zip){
zipOcurrences[i]++;
}
});
i++;
});
You can replace the codes in your zipArray array with objects containing the zipcode and the number of occurences
var url = 'https://data.baltimorecity.gov/resource/uds6-qsb6.json?$limit=50000';
var manyZipArray = [];
var zipArray = [];
$(document).ready(function() {
$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i++) {
manyZipArray.push(data[i].zip);
};
$.each(manyZipArray, function(i, el) {
// custom search in array
var index = arrayObjectIndexOf(zipArray, el, "code");
if (index === -1) {
zipArray.push({ code: el, occur: 1 });
}
else {
zipArray[index].occur++;
}
});
// custom sort to sort according to 'code' attribute
zipArray.sort(function(a, b) {
if (a.code< b.code) return -1;
if (a.code > b.code) return 1;
return 0;
});
for (var i = 0; i < zipArray.length; i++) {
$('#myList').append("<li>" + zipArray[i].code + " (" + zipArray[i].occur + ")</li>");
};
});
});
function arrayObjectIndexOf(myArray, searchTerm, property) {
for(var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 style="text-align: center" ;>Unique Zip Codes </h3>
<ul id="myList"></ul>

How to create a tabbed interface in Javascript

I'm trying to create a tabbed interface in Javascript which will allow a user to click on a button atop each interface in order to make the div under it become active while the other 'tabs'/divs recede to the background. I'm not quite sure I got that out right so attached is a screenshot of what I'm trying to make:
My code attaches one button -- beside the first div-- instead of all three and returns an error that says nodeChildren[j].getAttribute("data-tabname") is not a function although as far as I know, it seems it is.
I'll post my JavaScript code then add a link to fiddle where everything is.
function asTabs(node) {
var button = document.createElement("BUTTON");
var tempArray = [];
var nodeChildren = Array.prototype.slice.call(node.childNodes);
nodeChildren.filter(function(){
for (var i = 0; i < nodeChildren.length; i++) {
if (nodeChildren[i].nodeType === 1) {
tempArray += nodeChildren[i];
return tempArray;
}
}
});
nodeChildren.forEach(function (){
for (var j = 0; j < nodeChildren.length; j++) {
node.insertBefore(button, nodeChildren[j]);
var buttons = document.getElementsByTagName("button");
for (var k = 0; k < buttons.length; k++) {
buttons[k].innerHTML = nodeChildren[j].getAttribute("data-tabname").textContent;
}
}
});
var hide = nodeChildren.slice(1);
for (var l = 0; l < hide.length; l++) {
hide[l].className = "hide";
}
buttons[k].addEventListener("click", function (){
if (nodeChildren[j].className = "") {
nodeChildren[j].className = "hide";
}
else nodeChildren[j].className = "";
});
}
asTabs(document.querySelector("#wrapper"));
Then here's my fiddle containing comments explaining what is being tried to achieve on each line
https://jsfiddle.net/nmeri17/nmswdota/

Weird jquery error when checking for email data in textarea

Okay so i have a working example from jsfiddle which i cannot get to work. I used the code yesterday and now it simply doesnt work.
The code should check for duplicated emails and extract the emails from the first textarea to the second.
The link for Jsfiddle with working sample:
http://jsfiddle.net/49fkexu9/
I'm using the exact same code on my website, however it always says that theres no emails in the text.
Can anyone see an error in the code?
My website it:
http://truelads.com/email-extractor/
My html code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="email-extractor" class="email-extractor-textarea"></textarea>
<textarea id="email-extracted" class="email-extractor-textarea"></textarea>
My Jquery code:
function extractEmails(text) {
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
function eliminateDuplicates(arr) {
var i;
var len = arr.length;
var out = [];
var obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
var emailsFullList = [];
$('#email-extractor').keyup(function (index) {
var emails = extractEmails($(this).val());
console.log(emails);
if (!emails) {
$('#email-extracted').val('No emails found in text');
} else if (emails.length < 2000) {
var text = '';
for (var i = 0; i < emails.length; i++) {
text += emails[i] + ', ';
}
emailsFullListCheck = emailsFullList.concat(emails);
emailsFullListNone = eliminateDuplicates(emailsFullListCheck);
$('#email-extracted').val(emailsFullListNone);
} else {
$('#email-extracted').val('Please allow a max-limit of 2000 emails (' + emails.length + ').');
}
});
You have a section with the id email-extractor and a text area with the id email-extractor. You will need to change one of these then make sure your js lines up with the one you want to target

Categories