Dynamically add form elements with linked jQuery functions - javascript

I have a website where a user can configure a list of items before submitting the list. Each item is represented by a row of cascading comboboxes (each selection updates the possible values in the following comboboxes).
The user can add as many items as they want, configure them, then submit.
To do the add operation, I have a javascript function like this:
function newAction() {
// Get value of index so we can form our ids
var index = $("#ItemTable").find("#Item").length;
//copy the table row
var newItemRow = $("#Item:last-of-type").clone(true);
// Update all of the ids
var rowTextBefore = newItemRow.html();
var rowText = rowTextBefore.replace("[" + index - 1 + "]", "[" + index + "]");
newItemRow.html(rowText);
// Append the row to the end of the table
$("#ItemTable").append(newItemRow);
}
This is all working great.
But to enable the cascading comboboxes, there's a bunch of jQuery stuff that gets generated for each row. It looks like this:
jQuery(document).ready(function(){
jQuery('#Items[0]_Name').tComboBox({highlightFirst:false,
cascadeTo:'Items[0]_Accessories', data:[{...data here...]});
jQuery('#Items[0]_Accessories').tComboBox({highlightFirst:false,
// etc.
}
How can I clone this stuff along with the document elements so that my dynamically added rows implement the cascading comboboxes as well?

Related

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!

HTML Radio button table need to build it dynamically

I was doing some re factoring for a page, In that page I have bunch of radio buttons group.Data for the radio buttons comes from database and sometimes from cache layer.
I will probably be having close to 100 radio buttons. I need to arrange them in 5 column 20 rows.
Data population happens via arraylist. I was thinking for converting this arraylist into json and then using it to lay out the radio buttons in the HTML table format.
I know there are many plugins out there for building tables,however they are not meeting my requirements.How do I built 5 rows 10 column table with my data on the fly.
Something like
<tr>
<td>radio1</td>
<td>radio2</td>
<td>radio10</td>
</tr>
<tr>
<td>radio11</td>
<td>radio12</td>
<td>radio20</td>
The caveat here is that I do not know in advance as how much data I m going to get for the table.
Appreciate some thoughts.
Loop through your JSON object.
Use mod ('%') to append a new tr every ten items
Output td items (with content) to the last tr added.
If you're using jQuery, try something like this:
var holderDiv = $('#myDivId');
var i = 0;
var myData = jQuery.parseJSON(response);
$.each(myData, function(key,value) {
if(i == 0 || i == i%10){
holderDiv.append('<tr>');
}
holderDiv.find('tr:last-child').append('<td>' + value + '</td>');
i++;
}

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.

Adding new row on a table tbody by cloning the last row with events attached

I'm trying to clone the last row of a table with input fields that might have events attached, (in this case it's the keyup event). I also change the id's of the input fields to reflect the row where they are, something like:
table[0].field1,table[0].field2...table[1].field1...etc.
The problem is that I can add a row and it gets the events too, and when i write on the new cloned inputs they do start the events. But only on the first row created. If i create a new one, it will render the row with the inputs correctly but not the events. Here's the method:
addRow= function(tableid){
//jquery selector get table tbody with id
var table=jQuery('table[id="'+tableid+'"] >tbody');
//get last row containing input fields with tr class hoverTransparente
var lastRow=jQuery('table[id="'+tableid+'"] > tbody > tr:last');
//make a clone of the row
var clones = lastRow.clone(true); // copy events/children too
//get the input fields from the cloned row
var clonedInPuts=clones.find('input');
//for each input
jQuery(clonedInPuts).each(function (){
//set new input val to empty
jQuery(this).val("");
var inputId=jQuery(this).attr('id');
//table id
var table=inputId.split("[")[0];
//column id
var tableField=inputId.split(".")[1];
var idnumber=inputId.indexOf("[")+1;
//convert to number to make addition for new id index
var number = Number(inputId.charAt(idnumber))+1;
//replace id index with incrementaed value
var newId=inputId.replace(inputId.charAt(idnumber),number);
//change id for new one
jQuery(this).attr('id',newId);
//check if this variable exists/is not undefined
if(window["elements_"+table+"_"+tableField]){
window["elements_"+table+"_"+tableField].push(jQuery(this).get(0));
}
});
clones.appendTo(table);
}
Any ideas? when i try to debug in chrome the event onkeyup from the domtree of the input element is null but if i select using jquery directly and get the .data('events') method it does return an array with the events attached to the input field. Shouldn't the onkeyup return something different from null?
Ok, so the problem is not on this side but on the original method that creates the events in the original inputs of the existing rows. You need to do this:
var selectorStr='input[id^='+table+']&[id$='+tableField+']';
jQuery(document).on('keyup',selectorStr,function(event) {...})
instead of:
var elements=jQuery('input[id^='+table+']&[id$='+tableField+']');
elements.each(function() {
jQuery(this).keyup(function(){...})
});
This will solve the problem of adding new rows to the tablet and the input events actually search for newly added inputs.

Method call function in a table row clone editable

I have cloned the rows in my table editable.
The rows have 2 column editable, 1 with editable textarea and the other one with an input numer.
There is a function which sum the numbers in the two input numbers and give the total. You can try here, there is onblur : "submit"
I have cloned both Rows, they are editable but the function to calculate the Total does not work in the rows cloned.
How can i make my function working in the cloned rows?
you are cloning rows with id="sum", and you should not have duplicated ids in your page.
when i have to clone elements i generate dynamic ids so they don't get duplicated.
like this:
var lastid = $('[id^="clonedInput"]').length + 1;
$(".clonedInput").last().clone().attr('id', 'clonedInput' + lastid).appendTo("body")
you can test a full working example here: http://jsfiddle.net/RASG/MjMh5/
also, your jsfiddle is a total mess. please keep only the relevant code.
EDIT
ok, so you have other problems as well.
for instance, your function tally does not sum the cloned rows.
this function (not mention your whole code) could be a lot simpler.
function tally() {
var total = 0;
$('p.editable_number').each(function() {
total += parseInt($(this).text()) || 0;
$('#total').html(total);
})
}
test it here: http://jsfiddle.net/RASG/MA78A/

Categories