Hiding/Displaying columns using jQuery, checkboxes, and local storage - javascript

I have a page where a user submits a query using MVC, and the user can select the columns that are shown using checkboxes. After the user selects the query parameters and columns to view, the user is then sent to another page where a roster of individuals are shown. Checkbox data is stored using local storage, and used on the roster page where there are also checkboxes that the user can use to hide or display columns.
I have a working version, but the code looks awful and I think there is a better way to do this with less lines of code.
Here are the checkboxes used on the query page:
<div id="grpChkBox">
<input type="checkbox" class="columnSelect" name="fullName" /> Full Name
<input type="checkbox" class="columnSelect" name="type" /> Type
<input type="checkbox" class="columnSelect" name="ID" /> ID Number
</div>
Here is the script used to select columns and set values in local storage:
<script type ="text/javascript">
//Default is that all columns are selected
$("#grpChkBox input:checkbox").attr("checked", "checked");
localStorage.setItem("fullName", 1);
localStorage.setItem("type", 1);
localStorage.setItem("ID", 1);
$(function () {
if (localStorage.getItem("fullName") !== null) {
$("input[name='fullName']").attr("checked", "checked");
}
});
$("input[name='fullName']").click(function () {
if ($(this).is(":checked")) {localStorage.setItem("fullName", 1);}
else {localStorage.removeItem("fullName");}
});
$(function () {
if (localStorage.getItem("type") !== null) {$("input[name='type']").attr("checked", "checked");}
});
$("input[name='type']").click(function () {
if ($(this).is(":checked")) { localStorage.setItem("type", 1); }
else {localStorage.removeItem("type"); }
});
$(function () {
if (localStorage.getItem("ID")== null) { $("input[name='ID']").attr("checked", "checked"); }
});
$("input[name='ID']").click(function () {
if ($(this).is(":checked")) { localStorage.setItem("ID", 1); }
else { localStorage.removeItem("ID"); }
});
As you can see, I am creating a function for each checkbox and corresponding column, and there should be a way that I can enumerate columns/checkbox to do this with less lines of code. Just not sure how.
This is the HTML for the roster that is generated on the next page:
<table class="MainContent" style="width: 100%;" id="rosterTable">
<tr>
<th class="fullName" title="Full Name">Name</a></th>
<th class="type" title="Type">Type</a></th>
<th class="ID" title="ID Number">ID Number</a></th>
</tr>
<tr>
<td>Name 1</td>
<td>Type 1</td>
<td>ID Number 1</td>
</tr>
<tr>
<td>Name 2</td>
<td>Type 2</td>
<td>ID Number 2</td>
</tr>
</table>
It also has the same checkboxes as the previous page:
<div id="grpChkBox">
<input type="checkbox" class="columnSelect" name="fullName" /> Full Name
<input type="checkbox" class="columnSelect" name="type" /> Type
<input type="checkbox" class="columnSelect" name="ID" /> ID Number
</div>
And here's the script that reads local storage, and hides/displays columns after the roster is generated:
<script type="text/javascript">
// Reads local storage and check or unchecks, hides/displays
$(document).ready(function () {
if (localStorage.getItem("fullName") !== null) {
$("input[name='fullName']").attr("checked", "checked");
}
else {
var index = $("#rosterTable th").filter(".fullName").index();
$("#rosterTable").find('tr :nth-child(' + (index + 1) + ')').hide();
}
if (localStorage.getItem("type") !== null) {
$("input[name='type']").attr("checked", "checked");
}
else {
var index = $("#rosterTable th").filter(".type").index();
$("#rosterTable").find('tr :nth-child(' + (index + 1) + ')').hide();
}
if (localStorage.getItem("ID") !== null) { $("input[name='ID']").attr("checked", "checked"); }
else {
var index = $("#rosterTable th").filter(".ID").index();
$("#rosterTable").find('tr :nth-child(' + (index + 1) + ')').hide();
}
//After roster is generated users can hide display columns
$(function () {
var $chk = $("#grpChkBox input:checkbox");
var $tbl = $("#rosterTable");
var $tblhead = $("#rosterTable th");
//$chk.prop("checked", true);
$chk.click(function () {
var colToHide = $tblhead.filter("." + $(this).attr("name"));
var index = $(colToHide).index();
$tbl.find('tr :nth-child(' + (index + 1) + ')').toggle();
});
});
</script>
Once again, this should be done with less lines of code than using a case for each column and checkbox. I need to deploy this solution to multiple pages with different columns, so I would like to do this with more dynamic code. I'm pretty sure this could be done with less lines of code.
All help is appreciated

Looks like I found a solution myself. Here's what I did:
First, I replaced localStorage with sessionStorage.
I replaced the section where I set each sessionStorage object explicitly with this:
var selected = [];
$('#grpChkBox input[type=checkbox]').each(function () {
if ($(this).attr("checked")) {
sessionStorage.setItem(($(this).attr('name')), 1);
} else { sessionStorage.removeItem(($(this).attr('name'))); }
});
I replaced all the functions for checking the each sessionStorage value and populating each checkboxes with:
for (var i = 0, len = sessionStorage.length; i < len; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage[key];
//document.write(key + " => " + value + "\n");
if (sessionStorage.getItem(key) !== null) {
$("input[name='" + key + "']").attr("checked", "checked");
}
}
I replaced all the click functions for each checkbox with this:
$('#grpChkBox input[type=checkbox]').click(function () {
if ($(this.name).attr("checked")) {sessionStorage.setItem(this.name, 1); }
else {sessionStorage.removeItem(this.name);}
})
On the page where the roster is created, I replaced all the functions for checking the each sessionStorage value and populating each checkboxes with:
for (var i = 0, len = sessionStorage.length; i < len; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage[key];
//document.write(key + " => " + value + "\n");
if (sessionStorage.getItem(key) !== null) {
$("input[name='" + key + "']").attr("checked", "checked");
}
}
Instead of checking checkboxes that are checked, I am using unchecked values since the sessionStorage will have the corresponding keys/values removed. I replaced the many functions for determining which column is hidden with:
var selected = [];
$('#grpChkBox input:checkbox:not(:checked)').each(function() {
var index = $("#rosterTable th").filter("."+($(this).attr('name'))).index();
$("#rosterTable").find('tr :nth-child(' + (index + 1) + ')').hide();
});
That's it. The only thing that would make the over deployment of this simpler is if I could dynamically create checkboxes based on table header names.

Related

Add row with Jquery - Need to increment inputs names and onkeyup event caller

I am a bit new to JQuery and still trying to figure out how to add (clone) a table row at the end of the table and increment the input name="code10", onkeyup="recordTrans1(this.value)", and this div (<div class="txtHint3"></div>) inside a table cell.
Essentially I just want those 3 things to increment by 1 (e.g : name="code11", onkeyup="recordTrans2(this.value)", <div class="txtHint4"></div>, and so on...)
The code I have now is working perfectly to add or remove the table rows.
The problem I have is when I add a new table row, I don't see it in the "View source" of the page and the name="codeX", onkeyup, and div is not incrementing.
I tried a few different ways and can't seem to figure it out so any help would be greatly appreciated!
Here is the code I have to far :
<script>
jQuery.fn.addClone = function() {
return this.each(function() {
// get row for cloningg
var row = $(this).parents('tr');
var parent = {};
// use tbody or table parent
if ( $(row).parents('tbody').length>0) {
parent = $(row).parents('tbody');
} else {
parent = $(row).parents('table');
}
// inject clone
var copy = $(row).clone();
$(copy).addClass('sadey');
$(copy).addClass('isclone');
$(parent).append( copy );
// remove last td and replace with remove html
$('.sadey').children('td:last').remove();
$('.sadey').append('<td><button class="btn btn-block btn-danger" onclick="$(this).killClone()">Retirer</button></td>');
// increment all ids and names
var id = ($('.isclone').length + 1);
$('.sadey').find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
$(this).attr('id',tempId + '_' + id);
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
$(this).attr('name',tempName + '_' + id);
}
});
// remove active tag
$('.sadey').removeClass('sadey');
});
};
// remove a row and re-index the clones
jQuery.fn.killClone = function() {
var row = $(this).parents('tr');
$(row).remove();
// re-index
var id = 2;
$('.isclone').each(function() {
$(this).find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
tempId = tempId.split('_');
$(this).attr('id',tempId[0] + '_' + id);
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
tempName = tempName.split('_');
$(this).attr('name',tempName[0] + '_' + id);
}
});
id++;
});
};
</script>
And here's the HTML :
<table class="table table-striped" id="FinancialDataTable">
<thead>
<tr>
<th style="width: 10%;">Code</th>
<th style="width: 5%;">Qté</th>
<th>Produit</th>
<th>Description</th>
<th>Prix</th>
<th style="width: 10%;">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<input type="text" id="code10" name="code16" class="form-control" onkeyup="recordTrans1(this.value)" />
</div>
</td>
<td>
<div class="form-group">
<input type="text" name="qte16" class="form-control" value="1" />
</div>
</td>
<div id="txtHint3">
<td></td>
<td> </td>
<td> </td>
</div>
<td><button type="button" class="btn btn-primary btn-sm" onClick="$(this).addClone();">Ajouter un autre article</button></td>
</tr>
</tbody>
</table>
You can not see the updated source code by
Right click -> View page source
Browser loads the source code in a new Tab again when you click it. So,
Instead of using it use Code Inspector
Right click -> Inspect element
To get onkeyup attribute updation, you can modify a part of your the code by this:
$('.sadey').find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
$(this).attr('id',tempId + '_' + id);
$(this).attr('onkeyup','recordTrans' + id + "()");
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
$(this).attr('name',tempName + '_' + id);
}
});

Check for editable column in a table with jQuery function

In the table the first column is editable and after edit it/change it I want to show the alert as Changed. I am calling the check function after 5000ms.
Adding Code Snippet for My code
Something I missed or wrong somewhere. Please Help.
Here is the Code.
var table = $("table tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
id = $tds.eq(0).text(),
product = $tds.eq(1).text();
$check = function() {
if(($tds.eq(0).text() != id) && ($tds.eq(1).text() != product)){
alert("Changed");
}
else{
alert("Not changed");
}
}
setInterval(function() { $check(); }, 5000);
alert(id + ":" + product);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td contentEditable>63</td>
<td>Computer</td>
</tr>
</tbody>
</table>
if(($tds.eq(0).text() != id) && ($tds.eq(1).text() != product)){
This only triggers when both fields changed, change it to a "||"
Also check out this: https://developer.mozilla.org/en-US/docs/Web/Events/input for capturing contenteditable changes.

How to check the Select all checkbox after checking all its child checkboxes?

I want to check all the checkboxes upon checking the "Selectall" checkbox and vice versa if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. If I uncheck any of it's child checkboxes then the "Select all" checkbox should also be unchecked.
In my code, all the things are working except one thing that
if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. Can anyone help me in making this thing workable for me. For your reference I'm giving my file code (HTML and Javascript code) here, so that you could test on your local machine.:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("#ckbCheckAll").prop("checked",false);
}
});
});
</script>
</head>
<body>
<input type="checkbox" id="ckbCheckAll" /> Check All
<p id="checkBoxes">
<input type="checkbox" class="checkBoxClass" id="Checkbox1" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox2" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox3" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox4" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox5" />
<br />
</p>
</body>
</html>
You can check how many checkboxes are there and how many are checked:
$(".checkBoxClass").change(function(){
var all = $('.checkBoxClass');
if (all.length === all.filter(':checked').length) {
$("#ckbCheckAll").prop("checked", true);
} else {
$("#ckbCheckAll").prop("checked", false);
}
});
Not sure if all can be just $(this);
In addition to the selectAll checkbox I have experimented with adding selectRow and selectCol checkboxes to get the same effect for each row and column of the grid of checkboxes.
see http://jsfiddle.net/wf_bitplan_com/snpc2L34/29/
/**
* http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-
* expression
* examples:
*
* var matches = getRegexMatches(/(dog)/, "dog boat, cat car dog");
* console.log(matches);
*
* var matches = getRegexMatches(/(dog|cat) (boat|car)/, "dog boat, cat car");
* console.log(matches);
*/
function getRegexMatches(regex, string) {
if(!(regex instanceof RegExp)) {
return "ERROR";
}
else {
if (!regex.global) {
// If global flag not set, create new one.
var flags = "g";
if (regex.ignoreCase) flags += "i";
if (regex.multiline) flags += "m";
if (regex.sticky) flags += "y";
regex = RegExp(regex.source, flags);
}
}
var matches = [];
var match = regex.exec(string);
while (match) {
if (match.length > 2) {
var group_matches = [];
for (var i = 1; i < match.length; i++) {
group_matches.push(match[i]);
}
matches.push(group_matches);
}
else {
matches.push(match[1]);
}
match = regex.exec(string);
}
return matches;
}
/**
* get the select_row or select_col checkboxes dependening on the selectType row/col
*/
function getSelectCheckboxes(selectType) {
var regex=new RegExp("select_"+selectType+"_");
var result= $('input').filter(function() {return this.id.match(regex);});
return result;
}
/**
* matrix selection logic
* the goal is to provide select all / select row x / select col x
* checkboxes that will allow to
* select all: select all grid elements
* select row: select the grid elements in the given row
* select col: select the grid elements in the given col
*
* There is a naming convention for the ids and css style classes of the the selectors and elements:
* select all -> id: selectall
* select row -> id: select_row_row e.g. select_row_2
* select col -> id: select_col_col e.g. select_col_3
* grid element -> class checkBoxClass col_col row_row e.g. checkBoxClass row_2 col_3
*/
$(document).ready(function () {
// handle click event for Select all check box
$("#selectall").click(function () {
// set the checked property of all grid elements to be the same as
// the state of the SelectAll check box
var state=$("#selectall").prop('checked');
$(".checkBoxClass").prop('checked', state);
getSelectCheckboxes('row').prop('checked', state);
getSelectCheckboxes('col').prop('checked', state);
});
// handle clicks within the grid
$(".checkBoxClass").on( "click", function() {
// get the list of grid checkbox elements
// all checkboxes
var all = $('.checkBoxClass');
// all select row check boxes
var rows = getSelectCheckboxes('row');
// all select columnn check boxes
var cols = getSelectCheckboxes('col');
// console.log("rows: "+rows.length+", cols:"+cols.length+" total: "+all.length);
// get the total number of checkboxes in the grid
var allLen=all.length;
// get the number of checkboxes in the checked state
var filterLen=all.filter(':checked').length;
// console.log(allLen+"-"+filterLen);
// if all checkboxes are in the checked state
// set the state of the selectAll checkbox to checked to be able
// to deselect all at once, otherwise set it to unchecked to be able to select all at once
if (allLen == filterLen) {
$("#selectall").prop("checked", true);
} else {
$("#selectall").prop("checked", false);
}
// now check the completeness of the rows
for (row = 0; row < rows.length; row++) {
var rowall=$('.row_'+row);
var rowchecked=rowall.filter(':checked');
if (rowall.length == rowchecked.length) {
$("#select_row_"+row).prop("checked", true);
} else {
$("#select_row_"+row).prop("checked", false);
}
}
});
$('input')
.filter(function() {
return this.id.match(/select_row_|select_col_/);
}).on( "click", function() {
var matchRowColArr=getRegexMatches(/select_(row|col)_([0-9]+)/,this.id);
var matchRowCol=matchRowColArr[0];
// console.log(matchRowCol);
if (matchRowCol.length==2) {
var selectType=matchRowCol[0]; // e.g. row
var selectIndex=matchRowCol[1]; // e.g. 2
// console.log(this.id+" clicked to select "+selectType+" "+selectIndex);
// e.g. .row_2
$("."+selectType+"_"+selectIndex)
.prop('checked', $("#select_"+selectType+"_"+selectIndex).prop('checked'));
}
});
});
Use jQuery( ":checkbox" )
Maybe you can look # selectors of jquery http://api.jquery.com/category/selectors/
//----------Select AllCheckBoxes Begin ------------------------
function toggleChkBox() {
$('#tblPermissionDetails td input:checkbox').prop('checked', $('#chkSelectAll')[0].checked);
}
//----------Select AllCheckBoxes End --------------------------
//----------Check/Uncheck SelectAll checkbox based on other checkboxes Begin----------------
$('#tblPermissionDetails td input:checkbox').change(function() {
if (!$(this).prop("checked")) {
$("#chkSelectAll").prop("checked", false);
} else {
var PermissionList = [];
var PermissionListChecked = [];
$('#tblPermissionDetails td input:checkbox').each(function() {
PermissionList.push(this.name);
})
$('#tblPermissionDetails td input:checkbox:checked').each(function() {
PermissionListChecked.push(this.name);
})
if (PermissionList.length == PermissionListChecked.length) {
$("#chkSelectAll").prop("checked", true);
}
}
});
//----------Check/Uncheck SelectAll checkbox based on other checkboxes End------------------
<table class="table table-striped" id="tblPermissionDetails">
<thead>
<tr>
<th>Sl.No</th>
<th>Permission</th>
<th>Description</th>
<th><input type="checkbox" id="chkSelectAll" onclick="toggleChkBox();" />(Select All)</th>
</tr>
</thead>
<tbody>
#{ int i = 1; List
<FDSApp.Models.RolePermissionDetailsModel> permissionModel = Model; foreach (var item in permissionModel) {
<tr>
<td>#i</td>
<td>#item.PermissionName</td>
<td>#item.Description</td>
<td>#Html.CheckBox(#item.PermissionId.ToString(), #item.IsEnabled == 0 ? false : true)</td>
</tr>
i = i + 1; } }
</tbody>
</table>

Javascript for each instead of multiple if

Please, give "direction where to go"
Many input rows. For each row is field class="row_changed"
If value in the field is higher than 0, then ajax pass entire row to php. Each row is included in <tr> </tr> For each <tr> id is set <tr id='row'>
At the moment I can do it only with many if
Need something like: if value in any of field field class="row_changed" is more than 0, then pass corresponding row (inside <tr id='row'>) to php.
Here is some information. Is it suitable for the described case?
<tr id='row1'>
<td>
<input type="text" name="row1[]" id="date_day1" class="row_changed1">
</td>
...
<td>
<input type="text" name="row1[]" id="is_row_changed1" size="1">
<script>
$(".row_changed1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
</td>
<tr>
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
});
var str = $("#row1 :input").serialize();
$("#load1_1").text(str);
}
if ($("#is_row_changed2").val() > 0) {
$.post("_autosave_array.php", $("#row2 :input").serialize(), function (data2) {
$('#load2').html(data2);
$('#is_row_changed2').val(0)
});
var str = $("#row2 :input").serialize();
$("#load2_1").text(str);
}
Something like this should do it:
function doPost(changedRowId,serializeRowId,resultId,serializeResultId){
if ($(changedRowId).val() > 0) {
$.post("_autosave_array.php", $(serializeRowId + ":input").serialize(), function (data2) {
$(resultId).html(data2);
$(changedRowId).val(0)
});
var str = $("#row2 :input").serialize();
$(serializeResultId).text(str);
}
var rowData = [{changedRowId: "#is_row_changed1", serializeRowId: "#row1", resultId: "#load1", serializeResultId: "#load1_1"},
{changedRowId: "#is_row_changed2", serializeRowId: "#row2 ", resultId: "#load2". serializeResultId: "#load2_1"}
];
for(var i = 0; i < rowData.length; ++i){
var data = rowData[i];
doPost(data.changedRowId,data.serializeRowId,data.resultId,data.serializeResultId);
}
I can see that all your input tags have the same name, you can select all of them by name then put your condition/logic inside
sample:
$("input[name='row1[]']").each(function(){
if($(this).val()>0){
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
}
});

how to call a function with parameters that is assigned to a variable in JQuery .each()?

How can I pass arguments to a function that is assigned to variable.
For example:
var updateDiv = function() {
var row = this;
var values = "";
$('input[type=text],textarea,input[type=radio]:checked,input[type=checkbox]:checked', this).each(function() {
if ($(this).val()!="" && $(this).val()!=null) {
if (values!="") values = values + ","+ $(this).val();
else values += $(this).val();
}
});
if (values!="") {
if(values.substring(0,1)==",") values = values.substring(1) +"<br>";
else values = values +"<br>";
}
$('.jist', row).append(values);
}
$('tr:has(input)').each(updateDiv);
$('tr:has(textarea)').each(updateDiv);
HTML:
<tr>
<td>ai</td><td> <input type="text" name="ai" id="ai"></td>
<td><input type="checkbox" name="ana" id="ana" value="N/A"></td>
<td><div class="jist"></div></td>
</tr>
I want to pass arguments to updateDiv -> updateDiv("mystring");
and I want to use "mystring" in the function this way - > $('.'+mystring, row).append(values);
Simple and Clean
Not sure how I missed the obvious here.
jQuery
var updateDiv = function(divClass) {
...
$(divClass, row).append(values);
}
$('tr:has(input)').each(function(){ updateDiv('.hist'); });
$('tr:has(textarea)').each(function(){ updateDiv('.something-else'); });
.
Global Variable Method
You could assign global variables with the class name. By defining the variable before each .each() the updateDiv function uses a different class name.
jQuery
var updateDiv = function() {
...
$(window.divClass, row).append(values);
}
window.divClass = '.hist';
$('tr:has(input)').each(updateDiv);
window.divClass = '.something-else';
$('tr:has(textarea)').each(updateDiv);​
.
HTML5 Data Method
You could assign values as data objects to the elements which are being called. I also cleaned up some of your selectors and jQuery redundancies.
Fiddle: http://jsfiddle.net/iambriansreed/KWCdn/
HTML
<table>
<tr data-update=".hist">
<td>AutoI</td>
<td> <input type="text" name="autoIH_complaint" id="autoIH_complaint"></td>
<td><input class="NA" type="checkbox" name="autoINA" id="autoINA" value="N/A"></td>
<td><div class="hist"></div></td>
</tr>
</table>
jQuery
var updateDiv = function() {
var row = this, values = "";
$('input:text,textarea,:radio:checked,:checkbox:checked', this).each(function() {
if (this.value != "" && this.value != null) {
if (values != "") values = values + "," + this.value;
else values += this.value;
}
});
if (values != "") {
if (values.substring(0, 1) == ",") values = values.substring(1) + "<br>";
else values = values + "<br>";
}
$(row.data('update'), row).append(values);
}
$('tr:has(input)').each(updateDiv);
$('tr:has(textarea)').each(updateDiv);​
We can pass the index into the function, much like jQuery's .each() method.
<div class="test">1</div>
<div class="test">2</div>​
This will alert "0" and then "1" for the indexes.
var updateDiv = function( index )
{
alert( index );
}
$('.test').each(updateDiv);
If you pass in strings as parameters, .each(updateDiv("string1")) it is evaluates the function first.

Categories