how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:
$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
var itemName = $.each(json[1], function(i, val){
})
var itemDescription = $.each(json[2], function(i, val){
})
var itemLink = $.each(json[3], function(i, val){
})
console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
})//EOF getJSON
});//EOF button click
I believe this is what you are looking for:
for (var i = 0; i < itemName.length; i++) {
console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]);
}
If arrays have the same length, you could use map
var result = $.map(json[1], function(i, val){
var row = val + " " + json[2][i] + " " + json[3][i];
console.log(row);
return row;
}
Also you can use that result later, e.g.
console.log(result[0]);
Using es6 you can do the following:
(in your getJson callback):
function (json) {
const [value, optionsJ, descriptionsJ, linksJ] = json;
let whatIwant = [];
// choose one to loop through since you know they will all be the same length:
optionsJ.forEach(function (option, index) {
whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
});
// use whatIwant here**
}
Your new whatIwant array will then contain objects for each set.
Related
I have an HTML/CSS search bar where people can type a keyword and, on click, my Open States JSON API code returns New Jersey state bills that match that keyword.
Search Bar Screenshot
Screenshot of a Result
I want the bill titles that are returned to be hyperlinked to their page on the New Jersey state legislature site, but I can only find instructions for how to hyperlink a return with a static site.
Here is my JavaScript code so far (with API key removed):
e.preventDefault();
// console.log($("#billID").val());
var billSearchValue = $("#billID").val();
if(billSearchValue=='')
{
alert("Enter Desired Query Parameters");
} else{
// console.log(billSearchValue);
}
var searchQuery = "&q=" + billSearchValue;
var baseUrl = "http://openstates.org/api/v1/bills/?state=nj";
var apiKey = "";
var apiKeyParam = "&apikey=";
var apiKeyParams = apiKeyParam + apiKey;
var urlJSON = baseUrl + searchQuery + apiKeyParam + apiKey;
// console.log(urlJSON);
$.getJSON(urlJSON, function (data) {
var billsVar = [];
$.each(data, function(key, val) {
billsVar.push(val);
});
for (var i = 0; i < billsVar.length; i++) {
var billList = "<li>Bill <ul class=\"ul-sub\">"
var billTitle = "<li><strong>Bill Title</strong>: " + billsVar[i]['title'] + "</li>";
var billCreatedAt = "<li><strong>Bill Created</strong>: " + billsVar[i]['created_at'] + "</li>";
var billUpdatedAt = "<li><strong>Bill Updated</strong>: " + billsVar[i]['updated_at'] + "</li>";
var billID = "<li><strong>ID</strong>: " + billsVar[i]['id'] + "</li>";
var billChamber = "<li><strong>Bill Chamber</strong>: " + billsVar[i]['chamber'] + "</li>";
var billState = "<li><strong>Bill State (Probably Don't Want/Need This)</strong>: " + billsVar[i]['state'] + "</li>";
var billSession = "<li><strong>Bill Session</strong>: " + billsVar[i]['session'] + "</li>";
var billType = "<li><strong>Bill Type</strong>: " + billsVar[i]['type'] + "</li>";
var billSubjects = "<li><strong>Subjects</strong>: " + billsVar[i]['subjects'] + "</li>";
var billBillID = "<li><strong>Bill ID</strong>: " + billsVar[i]['bill_id'] + "</li>";
var billOutput = billList + billTitle + billCreatedAt + billUpdatedAt + billID + billChamber + billState + billSession + billType + billSubjects + billBillID + "</ul></li>";
$("#jsonlist").append(billOutput);
}
});
})
});
After a bit of research I see that a bill hyperlink is like this:
http://openstates.org/nj/bills/{Bill Session}/{Bill ID}/
I can't test my code because I have no API key, but the solution could be something like:
var billTitle = '<li><strong>Bill Title</strong>: '
+ '<a href="http://openstates.org/nj/bills/' +
billsVar[i]['session'] + '/' + billsVar[i]['bill_id'].split(' ').join('') + '/">'
+ billsVar[i]['title'] + '</a></li>';
I want add "All" option to the existing dropdown as a first option. Pls help me
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.empty();
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
}
I want "All" to be the first option in select dropdown
Instead of empty() use .html() and pass the html of the All Option. This will clear the select first then will add all option and then will add other options, and will save you an unnecessary .empty() operation.
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.html('<option value="'+all+'">All</option>');
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
Try this: You can add ALL option just right after emptying the output variable as shown below -
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.empty();
output.append("<option value='ALL'></option");//add here
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
}
Try this:
$('#mysampledropdown').empty();
$.each(response.d, function(key, value) {
$("#mysampledropdown").append($("<option></option>").val(value.ID).html(value.text));
});
$('<option>').val("").text('--ALL--').prependTo('#mysampledropdown');
I have some of this Code:
function writeIslamicDate(adjustment) {
var wdNames = new Array("Ahad","Ithnin","Thulatha","Arbaa","Khams","Jumuah","Sabt");
var iMonthNames = new Array("Muharram","Safar","Rabi'ul Awwal","Rabi'ul Akhir",
"Jumadal Ula","Jumadal Akhira","Rajab","Sha'ban",
"Ramadan","Shawwal","Dhul Qa'ada","Dhul Hijja");
var iDate = kuwaiticalendar(adjustment);
var outputIslamicDate = wdNames[iDate[4]] + ", " + (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
document.write(writeIslamicDate());
Output : Ithnin, 23 Ramadan 1435 AH
?
I want to replace 23 with bengali number ২,৩ ///// or two, three
I watch and try a lot of but couldn't success.. Is there are any to solve this ?
Thanks.
I do like
var someString = (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " হিজরী";
var outputIslamicDate = somestring.replace(/1/g, "১").replace(/4/g, "৪");
return outputIslamicDate;
but it's not work...
Use regex and the global flag:
str.replace(/word/g, 'word2');
I'm just starting with Node and I am getting stuck with managing the "callback hell." I have successfully managed to work with the Event emitter in order to fire an event in the main js file from a module, but I am unable to figure out how to work the scoping to fire an event from within a callback in the module. Furthermore, I am having issues calling a prototype function from within the call back in the module.
Specifically, here:
rows.forEach(function(thisRow, index, array) {
myDb.query("SELECT COUNT(a.studentID) as total, m.fName, m.lName, m.id " +
"from `absences` a join `members` m on a.studentID = m.id " +
"where a.aDate>=" + myDb.escape(thisRow['beginDate']) + " and " +
"a.aDate<=" + myDb.escape(thisRow['endDate']) + " and a.aDate<'" + today + "' and m.memGroup = " + myDb.escape(thisRow['orchName']) +
"GROUP BY a.studentID ORDER BY total DESC", function(error, row){
if(row.length > 0) {
retValues.push({"fullName": thisRow.fullName, "shortName": thisRow.shortName, "absences": row});
}
if (index === array.length - 1) {
//This call to this fails because, I believe, it is out of scope.
//How can I access this? OR how can I emit an event here that will
//trigger the listener in the index.js?
this._alertServer;
console.log(retValues);
console.log("Done");
}
});
});
The complete code can be found at:
http://pastebin.com/Gw6kzugk
EDIT - The possible answers above are exactly what you should be looking for. Below is what I ended up doing in my situation. Thanks All!
As explained in the comments, you can't use this inside a callback. You need to capture it outside of the callback, like this:
rows.forEach(function(thisRow, index, array) {
var self = this; // the critical line
myDb.query("SELECT COUNT(a.studentID) as total, m.fName, m.lName, m.id " +
"from `absences` a join `members` m on a.studentID = m.id " +
"where a.aDate>=" + myDb.escape(thisRow['beginDate']) + " and " +
"a.aDate<=" + myDb.escape(thisRow['endDate']) + " and a.aDate<'" + today + "' and m.memGroup = " + myDb.escape(thisRow['orchName']) +
"GROUP BY a.studentID ORDER BY total DESC", function(error, row){
if(row.length > 0) {
retValues.push({"fullName": thisRow.fullName, "shortName": thisRow.shortName, "absences": row});
}
if (index === array.length - 1) {
// Use self here, not this
self._alertServer;
console.log(retValues);
console.log("Done");
}
});
});
Although it may not be the most elegant want to approach this situation, what I ended up doing was passing this in a context function a la the short amount of time I spent programming Android programs.
_getAttendanceBySession = function(err, rows, retValue, context) {
/*
Gets attendance for each session given
err -> Errors returned from last mySQL query
rows -> JS Object of session list
retValue -> string being passed to webserver
context -> 'this'
*/
var tmpHTML;
tmpHTML = retValue;
myDb.getConnection(function(err, conn) {
rows.forEach(function(thisRow, index, array) {
conn.query("SELECT COUNT(a.studentID) as total, m.fName, m.lName, m.id from `absences` a join `members` m on a.studentID = m.id where a.aDate>=" + (myDb.escape(thisRow.beginDate)) + " and a.aDate<=" + (myDb.escape(thisRow.endDate)) + " and a.aDate<'" + today + "' and m.memGroup = " + (myDb.escape(thisRow.orchName)) + " GROUP BY a.studentID ORDER BY total DESC", function(error, row) {
if (row.length > 0) {
tmpHTML = tmpHTML + ("<h3 class='text-center'>" + thisRow.fullName + "</h3><div class='panel-group' id='" + thisRow.shortName + "'>");
row.forEach(function(studentRow, index2, array2) {
var tmpLabel;
if (studentRow.total === 1) {
tmpLabel = 'label-default';
} else if (studentRow.total === 2) {
tmpLabel = 'label-warning';
} else {
tmpLabel = 'label-danger';
}
tmpHTML = tmpHTML + ("<div class='panel panel-default'><div class='panel-heading'><a class='attendance-link panel-title' data-toggle='collapse' data-parent='#" + thisRow.shortName + "' href='#" + studentRow.id + "-details'><span class='label pull-left " + tmpLabel + "'>" + studentRow.total + "</span>" + studentRow.fName + " " + studentRow.lName + "</a></div><div class='panel-body collapse' id='" + studentRow.id + "-details'></div></div>");
if (index2 === array2.length - 1) {
tmpHTML = tmpHTML + "</div>";
}
});
}
if (index === array.length - 1) {
conn.release();
context.emit("send-page", tmpHTML);
}
});
});
});
};
I am trying to implement a search box that will search a particular play (AJAX file) for any instances of the word, if the word is found it then outputs that line. My problem is that if no results are found of the word instead of continuing to show the entire play it outputs the last line of the play only.
My function:
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", current_play_dom).each(function () {
var line = this;
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query, '<span class="query_match">' + query + '</span>');
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++
$("#mainOutput").append("<br /><p class='speaker_match'>"+ $(line).parent().find('SPEAKER').text() +"</p>");
$("#mainOutput").append("<p class='act_match'>"+ $(line).parent().parent().parent().children(':first-child').text()+"</p>");
$("#mainOutput").append("<p class='scene_match'>"+ $(line).parent().parent().children(':first-child').text() +"</p>");
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#mainOutput").append("<br>");
}
});
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#sideInfo").append("<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
Also as a side question is there a neater way to do this:
$(line).parent().parent().parent().children(':first-child')