acts_as_votable javascript html table - javascript

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.
I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.
I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?
Here is the dashboard.js:
var insertDest = function(dest) {
// Find a <table> element with id="myTable":
var table = document.getElementById("destTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var name_cell = row.insertCell(0);
var address_cell = row.insertCell(1);
// var delete_cell = row.insertCell(2);
var like_cell = row.insertCell(2);
like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
var like_count_cell = row.insertCell(3);
like_count_cell.innerHTML= 0;
// Add some text to the new cells:
name_cell.innerHTML = dest.name;
address_cell.innerHTML = dest.address;
// delete_cell.innerHTML = "<div class='del'>x</div>";
addMarker(dest.address,map);
};
var insertAllDest = function(trip){
var d = trip.destinations;
for (i in d){
insertDest(d[i]);
}
};

However, does this mean I need to write a 'attachLikeHandler' function
to deal with what happens when the like button is clicked?
Yes:
$(".like").on('click', function() {
$.ajax({
method: "PUT",
url: "/photos/" + $(this).attr("id"),
success: function(msg_from_server) {
alert(msg_from_server); //"Thanks for voting!" or "Sorry, you already voted!"
}
});
});
If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

Related

how to replace old table rows with new rows using javascript

I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});

Duplication of rows in Javascript Table

I am quite new to javascript and for some time now i cant figure a solution to a problem that i have on my own. The web application i am building is using javavascript and Firebase. I am creating a table that pulls some data from mysql and display them as a table in my website. The table consists of three columns ID,NAME, AND SURNAME.Along with that i am also creating a new column called Recipient that consists of buttons. The table looks like this:
I give a different value to each of the buttons, the value of each button is the number of the ID that is in the same row as the current button. For example the first button has a value = 2, the 3rd a value = 123. Al the buttons have an id = contact
The source code of the table is
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName`,`storagefolder` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table class=table table-condensed>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Recipient</th>
</tr>
</thead>";
while($record = mysql_fetch_array($clients)){
echo "<action=usersfiles.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<button value=".$record['ID']." id=contact>Folder Data</button>"." </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
When i click on a button from the table the application get the value of the corresponding button and store it in a variable, then it sends the variable to a function that will drug all the files from firebase database that are store in the folder with the same name as the variable, And then it will display them.
My firebase Database
So for example when I click on the button of the first column I will get the files that are stored in the folder with name 2 form firebase.database. The result of after I click the first button will be this:
My source code works fines as it gets the files from the corresponding folders from firebase.database. The problem that i have is when i dont refresh the page and i click a button again then the outpout will be the result of the previous button click plus the new one. For example if i dont refresh my page and i click the second button to get the files from the file from database with the name = 3 the outpout will be :
The outpout is a merging of all the results that i have oupouted so far. If i refresh my page and click on the second button now i will get the result i want which it is:
How can i edit my source code so the tables wont merge?
My source code is the follwing:
Source code of saving the value after button is clicked and passsing it to function:
var contactName; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contact"]').click(function() {
contactName = $(this).val(); //set var contactName to value of the pressed button
store(contactName);
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
Source code of function receiving the value and displays the corresponding file from firebase database:
function store(value){
var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref().child(`files/${value}/`);
var rowIndex = 1;
databaseRef.once('value',function(snapshot){
snapshot.forEach(function(childsnapshot) {
var childKey = childsnapshot.key;
var childData = childsnapshot.val();
//var urls = childData.url;
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var button = row.insertCell(2);
var itd = document.createElement('input');
itd.setAttribute("type","button");
itd.setAttribute("value","View");
itd.onclick=function () {
window.open(childData.url);
};
cellId.appendChild(document.createTextNode(childData.filename));
cellName.appendChild(document.createTextNode(childData.created));
button.appendChild(itd);
rowIndex = rowIndex+1;
//document.write(username);
})
});
}
Thanks in Regards
You only append data to the existing table, without ever removing existing rows in the table:
var row = tblUsers.insertRow(rowIndex);
You should make sure to remove all existing rows before adding the new one(s):
for (var i = tblUsers.rows.length; i >= 0; i--) {
tblUsers.deleteRow(i - 1);
}

How to get complete data from (html) bootstrap table when pagination is turned on

I am using bootstrap table in my web page and want to get complete textual data from all table cells, when pagination is on. I have tried the following method and it returns all the data:
var data = $('#' + tableID).bootstrapTable('getData')
Now when i traverse data object to get value for every cell it works fine but, for those cells which have some nested html , for example:
<td class="danger">cell 4</td>
<td>
google
</td>
Now, in this case, i want to get value for second cell as google but it returns me whole html as
google
Any idea, how i can get only textual value.
I can't do any server side operation, I have to achieve this using javascript/jquery. I have also tried using jquery:
function getColData(tableID,colIndex) {
var colArray = $('#' + tableID + ' td:nth-child'+'('+colIndex+')').map(function(){
return $(this).text();
}).get();
return colArray
}
it returns data correctly but only which is visible on active page and i want all the data.
Based on your file on JSFiddle I have modified the JS part as follows, this will get you the text on every td(i.e. text or text content) and not the values of their attributes. Basically this traverses through the DOM searching for tags embedded in ones - except for those on the table header - then obtains the text value.
var table = $('#table'), button = $('#button');
button.click(function() {
var data = [];
table.find('tr:not(:first)').each(function(i, row) {
var cols = [];
$(this).find('td').each(function(i, col) {
cols.push($(this).text());
});
data.push(cols);
});
alert(data);
});
You can see it in action here
UPDATE:
This will get you all data regardless of pagination, also it will strip tags and nested tags.
var table = $('#table'), button = $('#button');
button.click(function() {
var messedData = table.bootstrapTable('getData');
var data = [];
$.each(messedData, function(i, row) {
var rowData = {
'name': row['0'],
'star': row['1'],
'forks': row['2'],
'desc': row['3'],
}
for (prop in rowData) {
var tmp = document.createElement("div");
tmp.innerHTML = rowData[prop];
rowData[prop] = tmp.textContent || tmp.innerText || "";
}
data.push(rowData);
});
console.log(data);
});
You can see it here
Since the actual data is coming in as a string, I don't think bootstrap-table can't differentiate it from the other data. The simple solution I can think of is to use substring() to extract the data from the cells that contain custom html.
http://jsfiddle.net/vwg5Lefz/
The alternative is to go through the generated table <td> and use text() to get the text data from the cells.
http://jsfiddle.net/n0djy60v/

Javascript not recognizing a created button

I have some Javascript that creates a button when an ajax form submission is successful. When the page is reloaded the button will be rendered to the page.
Its a simple form javascript combination to add an item to a table with a remove button to remove that item.
I've run a diff tool and there aren't any differences between submitting the form and creating the button, and reloading the page with the button already created. So that leads me to believe Javascript isn't recognizing the button being created.
Here is some code:
Here is my javascript method
$('button#proxy_remove_given').click(function() {
$.ajax({
url: $('button#proxy_remove_given').attr('action'),
type: 'POST',
data: $('form#proxy_submit_form').serialize(),
success: function(responce) {
if ("Success" == responce) {
var username = $('button#proxy_remove_given').attr('name');
$('#given_proxy_access_table tr#'+username).remove();
var table_length = document.getElementById("given_proxy_access_table").rows.length;
if (table_length == 0) {
var table = document.getElementById("given_proxy_access_table");
var new_row = table.insertRow(0);
new_row.id = "NoProxyRow";
var cell1 = new_row.insertCell(0);
var cell2 = new_row.insertCell(1);
cell1.innerHTML = "<p>No Proxies Found</p>";
cell2.innerHTML = "<button data-toggle=\"collapse\" data-target=\"#add\">Add</button>";
}
}
}
});
});
Here is the javascript to add the button
$('button#proxy_submit').click(function() {
$.ajax({
url:'proxy/submit',
type: 'POST',
data: $('form#proxy_submit_form').serialize(),
success: function(responce) {
if ("Success" == responce) {
var table = document.getElementById("given_proxy_access_table");
if (table.rows.length == 1) {
if (table.rows[0].id == "NoProxyRow") {
document.getElementById("given_proxy_access_table").deleteRow(0);
}
}
var username = document.getElementById('id_proxy_username').value
var new_row = table.insertRow();
new_row.id = username;
var cell1 = new_row.insertCell(0);
var cell2 = new_row.insertCell(1);
cell1.innerHTML = "<p>{0}</p>".replace(/\{0\}/g,username);
cell2.innerHTML = "<button type=\"submit\" name=\"{0}\" id=\"proxy_remove_given\" action=\"proxy/remove/given/{0}\">Remove</button>".replace(/\{0\}/g,username);
document.getElementById("proxy_submit_form").reset();
}
}
});
});
Any idea why javascript wouldn't recognize a button being created?
<button type="submit" name="MikeC" id="proxy_remove_given" action="proxy/remove/given/MikeC">Remove</button>
EDIT:
Why isn't this
$('button#proxy_remove_given').click(function()
picking up this
<button type="submit" name="MikeC" id="proxy_remove_given" action="proxy/remove/given/MikeC">Remove</button>
when I add the button to the page
but it picks up the button call when I reload the page
It sort of depends how your code is structured but I’m guessing your click listener wont find the button because it doesnt exist yet.
$('button#proxy_remove_given') looks for the button but it isn’t there yet. You should put your click listener after the button has been added.
if I got your point
1st: if you use submit form or button type submit click without reloading the page you can use e.preventDefault()
2nd: with dynamically generated elements you should use
$('body').on('click', 'selector' , function(){});
take a look at Event binding on dynamically created elements?

SharePoint List, display calculated field in edit form

I have several SharePoint lists that have a calculated field, which is calculated from the ID field, e.g. if the ID is 13, the calculated field is "XX00013", where "XX" indicates the purpose of this particular list.
By default, in the Display From, this "XX00013" is shown.
How can I make it shown as read-only in the Edit Form too? So that the user who is editing the entry always can see which entry s/he is editing?
I don't think I can edit the EditForm, as it's restricted by the webmaster.
I do have access to Content Editor Web Part to edit some javascript code.
Any suggestions?
I tried to put following code in the in the Content Editor Web Part, which is added to the Edit page. It works so far that the "XX00013" is shown as ready-only in the Edit form. This solution is just a walk-around.
Still the question of in general how to show calculated field remains.
<script type="text/javascript">
function DisplayID(){
var regex = new RegExp("[\\?&]"+"ID"+"=([^&#]*)");
var qs = regex.exec(window.location.href);
var sID = qs[1];
var stID="XX";
var nLength=5-sID.length;
var i=0;
do{
stID=stID.concat("0");
i++;
}while (i<nLength)
stID=stID.concat(sID);
var TD1 = document.createElement("TD");
TD1.className = "ms-formlabel";
TD1.innerHTML = "<h3 class='ms-standardheader'>XX_ID</h3>";
var TD2 = document.createElement("TD");
TD2.className = "ms-formbody";
TD2.innerHTML = stID;
var IdRow = document.createElement("TR");
IdRow.appendChild(TD1);
IdRow.appendChild(TD2);
var ItemBody = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0];
ItemBody.insertBefore(IdRow,ItemBody.firstChild);
}
_spBodyOnLoadFunctionNames.push("DisplayID");
</script>

Categories