Get index of td elements in table using Javascript or jQuery - javascript

So I have a table.. It's in jade templating format so i've not created a jsfiddle for it.
Anyhow, the user clicks a button within the table and this toggles a class which displays all the information to do with that table.
The user clicks and this code gets executed:
$(function() {
$('.information-button').click(function() {
detailsPopup(this);
});
});
The onclick calls the function below:
function detailsPopup(el) {
// $(el).find("td").each(function(index){
// var bookingData = $(this).html();
// })
array1.indexOf(td [ fromIndex])
console.log($(el));
$(".details--info, .overlay--contain").toggle('600');
}
The problem i'm having, is I need to loop through all the td elements of the booking, grab the index and pass it through the onclick event. So when I toggle the class that displays the information, it only shows the information for that table cell.
Anyone know how I can achieve this? Thanks!

use Index in jquery.
select parent and get index number.
i.e:
$(el).closest('tr').index();

Related

How can I modify a list item after I created it with jQuery?

This is my todo list what I made.
(To make my code more readable I tried to comment. I hope it worked.)
If you try my demo, you can add li items with the "add" button. And the li items has 2 more buttons.
I want to create a modify button to users with can modifying their list items. I have no idea what I can to do for this with jQuery.
Second problem is that list buttons don't work perfectly well. Because if I use once a delete button it change the done button to delete an item. But if I dont use the delete button, the done button is working well.
I dont know why, maybe the same class name is the problem?
Here is my demo in JS Bin:https://jsbin.com/natiziqawa/edit?html,js,output
$(document).ready(function(){
$("#add").click(function(){
// Created list elements and their's buttons
var list_item =document.createElement("li");
var remove_button=document.createElement("button");
var done_button=document.createElement("button");
// append the buttons some string to caption buttons
$(remove_button).append("Delete");
$(done_button).append("Done");
// added class name the items to to distinguish them
$(list_item).addClass("item")
$(remove_button).addClass("delete");
$(done_button).addClass("done");
// filled the created items with the input values
var list_text =$("#input").val();
var time=$("#time").val();
// filled the list item with their's buttons and class names and input values
$(list_item).append(time," : ",list_text,done_button,remove_button);
// finally fill the ul with list items but first check out what is written in the input
if(input.value==""){
alert("Please enter an activity")
}
// If the input has some value can go
else{
$("ul").append(list_item);
// after clicked, clear the input field
$("#input").val("");
// list item's buttons
$(".done").click(function(){
$(list_item).click(function(){
$(this).css("color","white")
$(this).css("text-decoration","line-through")
});
});
$(".delete").click(function(){
$(list_item).click(function(){
$(this).remove()
});
});
}
});// main function close
}); // document ready close
The idea behind my solution is to use the contenteditable attribute for the added fields. To do this, you need to dynamically wrap the first two fields in an additional div, as shown here:
$(list_item).append('<div class="edit_item" contenteditable="true">'+time+'</div>'," : ",'<div class="edit_item" contenteditable="true">'+list_text+'</div>',done_button,remove_button);
You will need to replace this code with your existing one. For a better understanding, this code is located in the comment: "// filled the list item with their's buttons and class names and input values"
Also, you need to add this rule to the css to align the fields:
.edit_item {
display: inline-block;
}
And regarding the second question:
You had a targeting problem. You must refer to the current list_item using the closest() method.
For mark:
$(".done").click(function(){
$(this).closest(list_item).css("color","white")
$(this).closest(list_item).css("text-decoration","line-through");
});
For removing:
$(".delete").click(function(){
$(this).closest(list_item).remove();
});

Mapping a new column header to newly added html table column

What I am trying to accomplish is to allow the user to generate a table on a page, allow user to create new column(s), and for the column names to show up, and be mapped to, the data in the same column.
Currently, I am able to build the table and I have a generated table that maps its column headers to a select box. I have a refresh button on this page, that when clicked, refreshes the select box headers (in case a user creates a new column).
When I refresh the select box, the correct headers drop down, but the data that should be selected along with them are not mapped (I can see this with my console.log statements) This only happens when I create a column.. the column is appended to the table, but when I do something like
$('#dropHeader').change( function() {
firstArray = [];
console.log('First Select Box Changed');
var table = document.getElementById("theTable");
currentValue1 = ($(this).val());
console.log(currentValue1);
var elem1 = $("#theTable td:contains("+ currentValue1 +")");
console.log(elem1);
var index1 = elem1.index('#theTable td');
console.log(index1);
index1+=1;
$("#theTable tr td:nth-child("+ index1 +")").each(function () {
firstArray.push($(this).text());
});
firstArray.shift();
});
This works only for columns that are originally a part of the table.
Something that might help is that the console.log jQuery selector statements that I documented:
Normal selector statement:
[td,prevObject: m.fn.init[1], context: document, selector: "#theTable td:contains(Header 2)"]
Column Added selector statement:
[prevObject: m.fn.init[1], context: document, selector: "#theTable td:contains(New Column↵)"]
I've looked at this one for a while, and the I believe the issue lies within the jQuery selector statement. One thing I notice is the return signal at the end of the jQuery selector statement.
Any help would be greatly appreciated! Thanks!

why data method not working properly while getting ID?

I am trying to get Id using data method of jquery.I saw One example which is working fine.
http://jsfiddle.net/4ajeB/6/
In this example when user click add button generate dynamic rows.there is icon on right side ":" it open pop up .on click edit it give the id of row.Actually In this example developer use this
$('.edit_h').data('originalId', id);
Same thing when I used in my example it gives last value.In other words if you generate three row and click any icon of row it show "tc_3" only.I also used same concept .But I don't know why my output come wrong.
http://jsfiddle.net/4ajeB/7/
$('.edit_h').click(function(){
alert("edit ID:"+$(this).data('originalId'));
})
The problem is that your are calling:
$('.edit_h').data('originalId', id);
every time you add a test case. As you only have one popup menu, you are replacing the data attribute on the menu each time, so the last one added will always be there.
The data attribute should be on the listitem not the popup, then when you click the listitem, retrieve the id and write it into the menu data attribute.
$(document).on("click", ".edit_delete_copyFunctiontiy_h", function (e) {
var id=$(this).data('originalid');
$('.edit_h').data('originalid', id);
$("#Mainnavpanel").popup("open", {
positionTo: $(this)
});
});
$('.edit_h').click(function(){
alert("edit ID: "+ $('.edit_h').data('originalid'));
})
Updated FIDDLE

HTML: Get value from input with no ID

Been looking around and I cant seem to find an answer to this so maybe im wording it wrong but here it goes.
So I have a table displaying data from a database. In jQuery I have made it so a row can be added with empty inputs and then submitted to the database, this works fine.
I am now attempting to be able to edit it. So each row will have a button to edit that row, the button will put the row values into inputs so you can change the value and update the database. How can I do this? I was looking into using this here but Im not sure how I can get the value of the input boxes without them having some sort of ID.
jQuery I was trying to use:
$('#tbl').on('click','.xx',function() {
$(this).siblings().each(
function(){
if ($(this).find('input').length){
$(this).text($(this).find('input').val());
}
else {
var t = $(this).text();
$(this).text('').append($('<input />',{'value' : t}).val(t));
}
});
});
Am I over thinking this? Should I just be grabbing the values and then putting them in pre-made input boxes?
Update:
HTML:
sb.AppendLine("<table style='width: 80%;'>")
sb.AppendLine("<tr class='inputRowbelow'>")
sb.AppendLine("<td style='width: 20%;' class='ui-widget-header ui-corner-all'>Area</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Details</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Options</td>")
sb.AppendLine("</tr>")
For Each w In workItems
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & w.area & "</td>")
sb.AppendLine("<td>" & w.details & "</td>")
sb.AppendLine("<td><a href='#' class='fg-button ui-state-default ui-corner-all edit'><img src='/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
Next
sb.AppendLine("</table>")
There are a couple of ways to do this, including changing your VB code to add extra data to the html, but I will answer this from a pure javascript/JQuery solution.
First of all you need to handle the click event for each edit button, after that you find the matching row, and then you can get the first to td elements of that row...
$(".edit").click(function(e){
e.preventDefault();//prevent the link from navigating the page
var button = $(this);//get the button element
var row = button.closest("tr");//get the row that the button belongs to
var cellArea = row.find("td:eq(0)");//get the first cell (area)
var cellDetails = row.find("td:eq(1)");//get the second cell (details)
//now you can change these to your inputs and process who you want
//something like this...
ConvertToInput(cellArea, "area");
ConvertToInput(cellDetails, "details");
});
function ConvertToInput(element, newId){
var input = $("<input/>");//create a new input element
input.attr("id", newId);//set an id so we can find it
var val = element.html();//get the current value of the cell
input.val(val);//set the input value to match the existing cell
element.html(input);//change the cell content to the new input element
}
Here is a working example
From that you can then do the saving that you say you have already implemented, using the ID values of each field to get the values to save.
Instead of using a For Each ... in ... Next loop, use a a For loop with a counter. give each button and each row an ID with the current counter value at the end. You can then use Jquery to make each row editable separately, because each row has a row number now.

jQuery autocomplete UI Widget- Perform jQuery select event on dynamically created table row element

I have a working jQuery autocomplete being performed on the text input of a table data element, txtRow1. The text data is remote, from a mysql database, and is returned by JSON as 'value' for the text input. The returned data includes another piece of text, which, via a select event within the autocomplete, is populated to the adjacent table data element tickerRow1.
With help from the SO community, the autocomplete is now live and working on all text input elements of a dynamically created table (so txtRow1 to txtRowN). There is javascript code to create and name the table elements txtRoxN + 1 and tickerRowN + 1.
However, I have a problem with the select event for the id of tickerRowN. Because it changes every time I add a row, I don't know how to call the select event for the specific id of the table data in question.
I have done a lot of searching around but as I am new to this, the only functions I have been able to find manipulate the element data when you know the id already. This id is dynamically created and so I don't know how to build the syntax.
Thankyou for your time.
UPDATE: with huge thanks to JK, the following example works. I now know about jsFiddle and will try to use this for all further questions. The following code works for my dynamic example, but I don't know why. Sigh.
jsFiddle working example
function getRowId(acInput){
//set prefix, get row number
var rowPrefix = 'txtRow';
var rowNum = acInput.attr("id").substring((rowPrefix.length));
return rowNum;
}
$("#txtRow1").autocomplete({
source: states,
minLength: 2,
select: function(event, ui) {
var tickerRow = "#tickerRow" + getRowId($(this));
//set ticker input
$(tickerRow).val(ui.item.label);
}
});
http://jsfiddle.net/jensbits/BjqNz/

Categories