I have an application using firebase which looks like this:
The tick boxes to the right hand side of each 'Book', when clicked, sends the value of the firebase object into a string as shown below:
When clicking these tick boxes, I would like the style of the box and content to change so they turn blue. I have added this piece of code into the on click event:
function select(data, book, key) {
//What I added
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
//
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
However, this only turns the first box blue. No matter which check box I click, the first one just changes to blue and the rest stay grey.
Here is the JS code which creates the checkbox icons and the JS to highlight the selected check boxes.
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
//This generates the 3 columns on the application page
for (var i = 0; i < 10 && i < list.length; i++) {
lis += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 10; i < 20 && i < list.length; i++) {
lis2 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 20; i < 30 && i < list.length; i++) {
lis3 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
};
//This creates the 3 icons of delete, clear and select.
function genLinks(key, bkName) {
var links = '';
links += '<i id="deleteBook" class="material-icons">delete</i> ';
links += '<i id="removeBook" class="material-icons">clear</i> ';
links += '<i id="selectBook" onclick="functionSelected()" class="material-icons">check</i>';
return links;
};
function del(key, bkName) {
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
//This is the function to select and insert the data into the string as well as highlight each checkbox
function select(data, book, key) {
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
refreshUI(list);
});
If anybody can help it will be much appreciated.
Thanks,
G
The only thing I can see is that you are using the same id tags for multiple different objects on the same page. If you use it at more than one place, use a class! You should never have more than one of the same id because you will be facing a lot of repeating problems..
Related
I have a datatable that is using standard features (pagination, sorting, searching, date range, etc.), but I also have a portion at the bottom of the table that displays the total by office. What I would like to implement, however, is a means of hiding any search results that would display as "0" for an office. For instance, if you search my table for "assistant" then Edinburgh, London, Singapore and Tokyo all display a result of "0" (since there are no assistants for any of those offices). Instead of showing those empty results how could I instead hide them?
Here is a link to my jsfiddle: https://jsfiddle.net/l337method/vhoupanz/
Here is my script:
var offices = api.column(2).data().sort().unique().toArray();
var totals = [];
for (var i = 0; i < offices.length; i++) totals.push(0);
api.rows({filter:'applied'}).every(function() {
var data = this.data();
totals[offices.indexOf(data[2])] += intVal(data[5]);
});
html = '';
for (var i = 0; i < offices.length; i++) {
html += '<br>' + offices[i] + ': ' + totals[i];
}
html += '<br'
$(api.column(4).footer()).html(html);
Try this:
html = '';
for (var i = 0; i < offices.length; i++) {
if(totals[i] > 0){
html += '<br>' + offices[i] + ': ' + totals[i];
}
}
html += '<br'
How about this:
html = [];
for (var i = 0; i < offices.length; i++) {
if (totals[i] > 0) html.push(offices[i] + ': ' + totals[i]);
}
$(api.column(4).footer()).html(html.length == 0?"":html.join('</br>'));
This code displays the content of JSON file by formatting every word into sentences and then into HTML. On mouseover, words become blue. On click they become red. The next thing I want to do is to display the translation of the words (already in the json array) onclick.
https://jsfiddle.net/ve64qvtm/
var json = [
[
["Peki", "Well"],
["nedir", "what"],
["bu", "it"],
...
]
];
var arr2 = [];
for (k = 0; k < json.length; k++) {
var arr = json[k];
arr2.push('<p>');
for (i = 0; i < arr.length; i++) {
if (arr[i][0].length == 1) {
arr2.push(arr[i][0]);
} else {
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
}
}
arr2.push('</p>');
}
document.getElementById("text").innerHTML = arr2.join('');
var words = [...document.getElementsByClassName("word")];
words.forEach(function(word) {
word.onclick = function() {
if (word.className == "clicked") {
word.className = 'notclicked';
}
if (word.className == "onmouse") {
word.className = 'clicked';
}
}
word.onmouseover = function onMouse() {
if (word.className != "clicked") {
word.className = 'onmouse';
}
}
word.onmouseout = function onMouse() {
if (word.className != "clicked") {
word.className = 'notclicked';
}
}
});
I have no idea how to do this as the text to display is a variable.
How am I supposed to do this?
How about using Twitter Bootstraps tooltip. Add jQuery, bootstraps JS and CSS; once all this is added you would need to edit the line
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
To something like
arr2.push(' <span class="notclicked word ' + i + '" data-toggle='tooltip' data-placement='top' title='YOUR_TRANSLATION_HERE'>' + arr[i][0] + '</span>');
EDIT 2 - Updated Link:
Here is a working example
Edit 3
I Would also add a bit of margin on top and bottom so that you donĀ“t get unexpected behaviour from the tooltips, just because there is no space.
I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.
I am using my function in onclick nav tabs event (when click on any tab this below function activates). I just want that no same name can twice be inserted into the dropdownlist. Below function is working just perfectly. I just need a check maybe like name.text != arr[i] something like that to prevent it to insert the same name twice in the list. Any help would be appreciated.
js:
<script>
$(".nav-tabs li").click
(
function()
{
var getnumber = document.getElementById("permanentno").value;
var getData = 'methodname=getList&no='+getnumber;
$.ajax
({
type: 'GET',
url: 'Dropdown List/List.php',
data: getData,
success: function(resp)
{
alert(resp); // names for example: mile,stone,
var arr = resp.split(",");
var list = $(".dropdownlist");
var html = "";
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
}
}
$(".dropdownlist").append(html);
}
});
}
);
</script>
You could keep track of the names with another array and IndexOf. Note that for IE<9 support you'll need a shiv to use it.
var names = [];
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0 && names.indexOf(name) == -1)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
names.push(name);
}
}
You can append options to the dropdownlist on the loop, and check repeated names using jQuery like:
var list = $(".dropdownlist");
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (name.length != 0 && !list.find("option[value='" + name + "']").length) {
var html = "<option value='" + name + "'>";
html += name;
html += "</option>";
list.append(html);
}
}
When utilizing eBay's API, the listings show using the low res thumbnail pictures, rather than the high res version that the seller uploaded. What must I alter in the code to fix this? I've looked at solutions on eBays API forum, but it doesn't seem to be relevant to the code used in the tutorial.
Javascript code:
<div id="api"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [
{"name":"MaxPrice",
"value":"500",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"MinPrice",
"value":"200",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"FreeShippingOnly",
"value":"true",
"paramName":"",
"paramValue":""},
{"name":"ListingType",
"value":["FixedPrice"],
"paramName":"",
"paramValue":""},
];
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APPNAME*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%205%2016gb%20unlocked&paginationInput.entriesPerPage=3>
</script>
By default the Finding API returns a 140px thumbnail. You will have to specify an outputSelector in your API call in order to retrieve a larger thumbnail (400px or 800px). Adding either outputSelector=PictureURLLarge or outputSelector=PictureURLSuperSize to the call should make it return a URL for a larger image.
I struggled with this for a long time too. Make these changes:
Replace item.galleryURL; with item.pictureURLSuperSize;
Add &outputSelector=PictureURLSuperSize right after &paginationInput.entriesPerPage=3
That should do the trick. Make sure to use the same capitalization structure.
I wrote a longer blog post about this with more examples here