Customizing JQuery Cloned row attributes - javascript

I have been researching the JQuery way to add table rows dynamically. One excellent thread is: How to Copy Table Row with clone in jquery and create new Unique Ids for the controls, with the last example being the one I am targeting in this post.
I have a fiddle giving an example of what I am trying to do. This fiddle does not work exactly yet, but I am working on it,
The main issue I am having is getting the table row copy to set different types of column elements id and default values, and even row attributes. In essence, how do I extend this to be more robust.
Thanks to Nick Craver, I am trying to use this:
// do Add row options
$("#Add").click(function() {
var rowCount = $('#secondaryEmails >tbody >tr').length;
var i = rowCount + 1;
alert('rowCount: ' + rowCount + ', new row: ' + i);
$("#secondaryEmails >tbody tr:first").clone().find("input").each(function() {
$(this).attr({
'id': function(_, id) {
return id + i
},
'name': function(_, name) {
return name + i
},
'value': ''
});
}).end().appendTo("#secondaryEmails >tbody");
});
which will copy and insert a row nicely, but if I have a row with a radio button, input box, and select list, I cannot figure out how to tell it to set the default value of each element depending on the type of element. I am trying to use a template row, but that means I need to set the style:display attribute on the row from none to table-cell. Again, how?
Please see the fiddle mentioned previously for a working example.

This is now showing the row: http://jsfiddle.net/EwQUW/5/
You would want to use .show() on the element to show it, which effectively sets the style to display:block instead of display:none;

Try this http://jsfiddle.net/EwQUW/3/
// do Add button options
$("#Add").click(function() {
var i = ($('#secondaryEmails >tbody >tr').length)+1;
$("#secondaryEmails >tbody tr:first").clone().find("input,select").each(function() {
//if(this).(':radio').
$(this).attr({
'id': function(_, id) {
return id + i;
},
'name': function(_, name) {
if($(this).attr("type") == "radio")
return name;
return name + i;
},
'value': ''
});
}).end().appendTo("#secondaryEmails >tbody").show();
});
// do update button options
$("#update").click(function() {
// find and display selected row data
alert('in Update');
var rowCount = $('#secondaryEmails >tbody >tr').length;
});
// do row double click options
// do row selected by either focusing on email or ship type elements

Related

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

jQuery TableSorter - textExtraction based on external variable

I have a TableSorted table, and in each TD element are five SPAN elements. Four are always hidden, but upon clicking a div outside the table, certain spans are hidden dependent on which div is clicked.
I have the table sorting fine, but what I need is for the textExtraction to grab a different SPAN, depending on the value of the div which has been selected.
I've tried the following to no avail:
textExtraction:function(node){
var filter=$("div.career a.sel").text();
if(filter=="a"){var theindex=0;}
if(filter=="b"){var theindex=1;}
if(filter=="c"){var theindex=2;}
if(filter=="d"){var theindex=3;}
if(filter=="e"){var theindex=4;}
return $(node).find("span").eq(theindex).text();
}
What is the best way to achieve this?
The textExtraction function is only called when tablesorter is initialized or updated. Try triggering an update after the selection has changed.
var indexes = 'abcde'.split(''),
// Is this a select box?
$sel = $("div.career a.sel").on('change', function(){
$('table').trigger('update');
});
$('table').tablesorter({
textExtraction: function(node){
// if this is a select, get val(), not text()
var filter = $sel.val(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Update: for a link, try this:
var indexes = 'abcde'.split(''),
$careers = $("div.career a").on('click',function(){
var searcher = $(this).attr("rel");
$("div.career a").removeClass("sel");
$(this).addClass("sel");
$("td.stat span").hide();
$("td.stat span.career_" + searcher).show();
});
$('table').tablesorter({
textExtraction: function(node){
// find selected
var filter = $careers.filter('.sel').text(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Note: Don't use live() in jQuery version 1.9+, it was removed.

Get An Element Within a Table Row

Firstly,
If possible, I would like to do this without JQuery, and purely Javascript.
Ok so I have an html table with rows getting added dynamically to it.
In each row is a:
Select Element (id = "ddFields")
Text Input Element (id = "tfValue")
Button Element (no id)
The Button Element removes the row for which it is situated
The Select Element has a default option of "" and then other 'valid' options
The Text Input is added to the row but it is hidden.
All elements are in the same
Basically I would like for the Select Element to show the hidden text input element if the selected index is != 0
so far I have this for my onchange function:
function itemChanged(dropdown) //called from itemChanged(this)
{
var cell = dropdown.parentNode;
var row = cell.parentNode;
var rowIndex = dropdown.parentNode.parentNode.rowIndex;
var index = dropdown.selectedIndex;
var option = dropdown.options[dropdown.selectedIndex].text;
if(index >0)
{
alert(row);
var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
alert(obj);
//row.getElementById("tfValue").hidden = "false"; //doesn't work
//row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
}
else
{
alert('none selected');
}
}
Finally figured it out. So here it is:
SCENARIO:
A table that has rows added to it dynamically.
In each row there is a select element and an input text element.
The select element changes text-value of the input text element based on the index of the select element.
in your select element set the onchange function to this:
onchange="selectionChanged(this)"
then create a javascript function shown below:
function selectionChanged(dropdown)
{
//get the currently selected index of the dropdown
var index = dropdown.selectedIndex;
//get the cell in which your dropdown is
var cell = dropdown.parentNode;located
//get the row of that cell
var row = cell.parentNode;
//get the array of all cells in that row
var cells = row.getElementsByTagName("td");
//my text-field is in the second cell
//get the first input element in the second cell
var textfield = cells[1].getElementsByTagName("input")[0];
//i use the first option of the dropdown as a default option with no value
if(index > 0)
{
textfield.value = "anything-you-want";
}
else
{
textfield.value = null;
}
}
Hope this helps whoever. It bugged me for a very long time. Thanks shub for the help! :)
first, I hope you are not repeating your ids. No two items should have the same id.
If you're iterating, create id1, id2, id3.
Also, this is not necessary but I suggest introducing your vars like this:
var a = x,
b = y,
c = z;
If you decide to use jQuery you could just do this:
$('#tableid').on('click','button',function(){
$(this).parent().parent().remove();
});
$('#tableid').on('change', 'select',function(){
if($(this).val()){ $(this).next().show(); }
});
Be sure to change #tableid to match your table's id.
This assumes the text input is the very next element after the select box. If not so, adjust as necessary or ask and I'll edit.

How the select the multiple Table data as per selected checkbox?

There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit
Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit

Remove selected items from other select inputs

I have a problem with select input items.
What I want to achieve is dynamically remove already selected options from other select boxes so that I cannot select same item on multiple boxes. The problem is that elements are loaded in array via AJAX and I need to fill the select input with options after. This makes it so much harder.
In short - How can I make sure that if I select one item in select it will be deleted on all others, but when I select something else the previous item will be shown again and so on...
I have a fiddle as well, this is how far I got: http://jsfiddle.net/P3j4L/
You can try something like this
function updateSelects()
{
$('.selectContainer .select').each(
function (i, elem)
{
// Get the currently selected value of this select
var $selected = $(elem).find("option:selected");
// Temp element for keeping options
var $opts = $("<div>");
// Loop the elements array
for (i = 0; i < selectElements.length; i++)
{
var value = selectElements[i];
// Check if the value has been selected in any select element
if ($selected.val() == value || !$('.select option[value=' + value + ']:selected').length)
{
// if not create an option and append to temp element
$opts.append('<option value="' + value + '">' + value + '</option>');
}
}
// replace the html of select with new options
$(elem).html($opts.html());
if ($selected.length)
{
// set the selected value if there is one
$(elem).val($selected.val());
}
else
{
// new select element. So remove its selected option from all other selects
$('.selectContainer .select').not(this).find('option[value=' + $(elem).val() + ']').remove();
}
}
);
}
see a demo here : http://jsfiddle.net/P3j4L/1/

Categories

Resources