JavaScript function onclick runs automatically - javascript

i have this code in while loop in JavaScript. As you can see i am adding every loop to with ID page, another divs. Every div has onclick handler which can execute MyFunction with variable. My problem is that, my script onlick runs automatically when my page is loaded. But i need to run MyFunction only if i click on the div.
Code:
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='" + MyFunction(variable) + "'>" + AnotherVariable + "</div>";
Thank you

You're a bit off ... try ...
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(" + variable + ")'>" + AnotherVariable + "</div>";
.. if you don't want the function to run.
In particular, look here:
"<div ... onclick='MyFunction(" + variable + ")'>"
UPDATE 1:
"Variable is string." Then, here's the modification:
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(\"" + variable + "\")'>" + AnotherVariable + "</div>";

Related

How to fetch the json array?

I have my external json and trying to fetch the json values dynamically in my javascript. I am able to fetch the first level values and when I try to fetch the array object, it is showing my result as undefined. However when I try this "alert(data.siteAttribute[0].data[0].label);" its returning the the value.
Here is the following that I have tried
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/naqzj", function(data) {
$(".test").html('<div class="card-deck">');
var output = "";
for (var i in data.siteAttribute) {
output += "<div class='col-md-4 col-lg-3'><div class='card site-attribute-card'>";
output += "<span class='sticker sticker-rounded sticker-top-right'><span class='inline-item'><img height='50' width='50' src='"+data.siteAttribute[i].data.imageURL +"'/></span></span>";
output += "<div class='card-body'> <div class='card-row'>"
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.label + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.value + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.operatinghours + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.hours + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.areaLabel + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.areaValue + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].dateModified + "</div>";
output +="<div class='card-text'>" + data.siteAttribute[i].date + "</div>";
output += "</div></div>";
output += "<div class='card-footer'>";
output += "<div class='card-title text-truncate' title='Card Title'>"+ data.siteAttribute[i].name + "<span class='label label-tag label-category right'><span class='label-item label-item-expand'>"+data.siteAttribute[i].status+"</span></span></div>";
output += "<div class='card-links'><a href='/group/retail/site-management-form'>Edit</a><a class='right' href='#'>View</a></div></div>"
output += "</div></div>";
}
$(".test .card-deck").append(output);
$(".test .card-deck").append('</div>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="test container">
</div>
Here is my sample fiddle for reference. I am missing the loop fro the array and have no clues on how to figure out. Thanks in advance!
data.siteAttribute[i].data is an array
So you can use data.siteAttribute[i].data[0] to get the first item or you'll have to loop through that data as well.
Looks like you are only having issues with having nested loops. To loop over an array of objects I suggest I suggest using Array.prototype.forEach. To simplify your demo I have removed all the HTML markup and nested two forEach loops to parse over the JSON data. Please review the demo and inline comments below:
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/naqzj", function(result) {
// Loop over the top level attributes
result.siteAttribute.forEach(function(attr) {
// Loop over the attribute `data` array
attr.data.forEach(function(attrData) {
// For demo purposes, loop over the inner data object and print its props and values
for (var key in attrData) {
console.log(key, ' -> ', attrData[key]);
}
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

how to check for changed values in firebase real time database and make them show up in html table?

I have been able to remove entries from the table once it's been removed on the database and also able to add entries once they've been edited.
how to check if data is already in html table using firebase real time database?
I am now looking for how to look for live changes to the database.
var database = firebase.database().ref().child('transactions');
database.on('child_added', function(snapshot){
var data = snapshot.val();
var content = '<tr id="'+snapshot.key+'">';
content += '<td>' + data.CustomerName + '</td>';//column2
content += '<td>' + data.TimeEffected + '</td>'; //column1
content += '<td>' + data.DateEffected + '</td>'; //column1
content += '<td>' + data.Successful + '</td>'; //column1
content += '</tr>';
$('#ex-table').append(content);
database.on('child_removed', function(snapshot){
$('#'+snapshot.key).remove()
});
});
I tried using this:
database.on('child_changed', function(snapshot){
$('#'+snapshot.key).change()
});
I tried putting it under the remove method but that has been unsuccessful.
The $('#'+snapshot.key) gets the correct element in the HTML, but jQuery's change() method does not do what you think it does. Read the linked documentation to learn what it actually does.
If you think about if for a moment this should make sense: how would a built-in method from jQuery know how to update your HTML structure?
Only your code knows what HTML it created for the data in the snapshot. You will need to replicate (some of) your code that creates the HTML in the child_added callback into the child_changed callback.
Something like this:
database.on('child_changed', function(snapshot){
var data = snapshot.val();
var content = '<tr id="'+snapshot.key+'">';
content += '<td>' + data.CustomerName + '</td>';//column2
content += '<td>' + data.TimeEffected + '</td>'; //column1
content += '<td>' + data.DateEffected + '</td>'; //column1
content += '<td>' + data.Successful + '</td>'; //column1
content += '</tr>';
$('#'+snapshot.key).replaceWith(content)
});

Get the ID from "append(<tr><td="ID">..."

I am filling a table with some data that I get from firebase database, and for that I am using append()
$("#table_body").append("<tr><td>" + nome + "</td>" +
"<td>" + marca + "</td>" +
"<td>" + modelo + "</td>" +
"<td>" + setor + "</td>" +
"<td>" + responsavel + "</td>" +
"<td><div buttons>"+
"<button>Delete</button>"+" "+
"<button>Edit</button>"+
"</div></td></tr>");
But then, I don't know how to use the "Remove" and "Edit" buttons on each row of the table, shouldn't I have the ID of each row? But then, how do I get the ID of each row if the rows are added dynamically?
You have an object ID from your data model ... add that as an attribute to the row.
Then use a traverse to closest() row to isolate instances
Following assumes a button with class added :
<tr data-id="idFromFirebaseObject">
....
<button class="delete-btn">Delete</button>
Then use event delegation to account for elements that don't yet exist at run time
$("#table_body").on('click','.delete-btn', function(e){
// "this" is element event occurred on
var $row = $(this).closest('tr'),
rowId = $row.data('id');
// do your thing with FB then in success callback remove row
....
$row.remove();
})

jQueryUI dialog not displaying

I am trying to generate a jQuery UI dialog using a function. The function is triggered by an onClick event and it is executing, but for some reason the dialog will not display. I'm sure it is something simple.
I would prefer to create the dialog in this way if possible as loading the dialog from a separate html page causes same origin issues on chrome. The code is part of a browser extension that can possibly be used offline so this way allows for that without the same origin restrictions.
I have already created a similar dialog of this nature that worked which had a parameter appended between tags. I have tried that with the current one and it has not worked.
I have the latest jQuery ui and jQuery libs added in the main page.
I'm new to javascript and jQuery but if anyone could provide some help I'd greatly appreciate it.
Thanks,
Joe
function imageSelection() {
var NewDialog = $('<div id="imageSelectionDialog"> ' +
"<ol id= \"selectable\">" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image1.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image2.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image3.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image4.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image5.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image6.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image7.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image8.jpg\"/></li>" +
"</ol>" +
"<form id=\"pieceSelection\">" +
"<div id=\"imageInput\">" +
"<input type=\"text\" id=\"image\" value=\"images/stock/walkin.jpg\"" +
"title=\"Select an image above or Paste a URL e.g http://server.com/path/to/image.jpg\"/>" +
"</div>" +
"<div id=\"radio\">" +
"<input type=\"radio\" id=\"radio1\" name=\"radio\" checked/>" +
"<label for=\"radio2\">x3</label>" +
"<input type=\"radio\" id=\"radio2\" name=\"radio\"/>" +
"<label for=\"radio3\">x4</label>" +
"<input type=\"radio\" id=\"radio3\" name=\"radio\"/>" +
"<label for=\"radio4\">x5</label>" +
"<input type=\"radio\" id=\"radio4\" name=\"radio\"/>" +
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
"<label for=\"radio6\">x7</label>" +
"<input type=\"radio\" id=\"radio6\" name=\"radio\"/>" +
"<label for=\"radio7\">x8</label>" +
"<input type=\"radio\" id=\"radio7\" name=\"radio\"/>" +
"<label for=\"radio8\">x9</label>" +
"</div>" +
"</form>" +
'</div> ');
NewDialog.dialog({
autoOpen: false,
modal: true,
height: 500,
width: 500,
title: 'Choose an image',
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
return false;
}​
You seem to have an unexpected 7 within your string which makes this concatenation invalid, causing a Uncaught SyntaxError: Unexpected string.
Change this:
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
to either this:
"<label for=\"radio5\">x6</label>" +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
or this:
"<label for=\"radio5\">x6</label>" + 7 +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
In addition you need to set autoOpen to true if you want the dialog to be visible immediately.
DEMO - Removing the 7 and set autoOpen to true
You do not seem to be appending the HTML to the DOM to make it work..''
Append it to the body before you assign it to a Do=ialog and it should work..
var html = '<div id="imageSelectionDialog"> ' +
//other html ;
$('body').append(html);
var NewDialog = $("#imageSelectionDialog");
// Code to Initialize the dialog

Javascript passing parameters from form to function --> update DB

can anyone help please. I have a form generated dynamically, when it is submitted it should send values to a function and add them back to a database. I'm having real problems getting this to work, it seems simple: 1. Form --> 2. submit received --> 3. update function. The code is below:
Dynamically generated form:
function renderResults(tx, rs) {
e = $('#status');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input value=\"" + r.name + "\" name=\"name\" />" +
"<input value=\"" + r.amount + "\" name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});
}
}
Handles the form submit and passes to function:
$('#theform').submit(function() {
updateRecord($('#thename').val(), $('#theamount').val());
});
Function to set values:
function updateRecord(id, name, amount) {
db.transaction(function(tx) {
tx.executeSql('UPDATE groupOne SET (name, amount) VALUES (?, ?) WHERE id=?', [name, amount, id], renderRecords);
});
}
The DB update code has the id set to 4 as a test just to see if anything happens to row 4, i've been fiddling with this line for ages to get it to work. If i set it to:
tx.executeSql('UPDATE groupOne SET name = 4, amount = 5 WHERE id=?', [id], renderRecords);
it will work with set values, but can someone help me get the form values into it please.
You are missing the row id in your jQuery selector. You are passing:
$('#thename').val();
But your field has an id of "thename" + r["id"]:
'<input type="text" ... id="thename' + r['id'] + '" ...>'
You need to get your value by passing the full input id.
$("#thename" + rowId).val();
Edit: Looking more closely at your code, I notice you are creating multiple forms with the same id, which is invalid html. I see now that you've got one form per record. Good, just lose the id from the form and its inputs. Instead, use names for the inputs.
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input name=\"name\" />" +
"<input name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});

Categories

Resources