The following are some of the most common javascript requirements a web programmer come across while creating the web page for the application. I am writing here for my own reference so that I don't want to do serarch every time when I need to implement these scenarios
1. To check/uncheck all checkboxes in a column of a grid while selecting header checkbox
At Row_DataBound event of the gridview
protected void gvSubContractorActivitiesRates_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { CheckBox chkHeader = (CheckBox)e.Row.FindControl("chkHeader); chkHeader.Attributes.Add("onclick", "CheckOrUncheckAll(" + chkHeader.ClientID +")"); } }
Javascript function
-------------------
function CheckOrUncheckAll(chkHeader) { var frm = document.forms[0]; for (i = 0; i < frm.elements.length; i++) { if (frm.elements[i].type == "checkbox") { frm.elements[i].checked = chkHeader.checked; } } }
2. Regular expression In Javascript
Suppose there are checkboxes in more than one column of the gridview or there are check boxes outside the gridview in the web page, if we used the above js function to check/uncheck the column of a gridview it will also change the state of the checkboxes outside this column of gridview as we are checking the checkboxes of the page by the type 'checkbox'. So what if we want to restrict to the state of the checkboxes affected by changing the header checkbox of the gridview by limitting only to that column.
We can use the regular expression class in the js.
RegExp is the class in javascript for regular expressions, here we can define our regular expressions and test for the pattern matching.
Suppose our checkbox column in the gridview is rendered in the browser as 'someCharacters'+chkSelectLowest as always. Then we can define a regular expression for this id of checkboxes and test for the match.
i.e
var pattern = new RegExp("[\w\d_]+chkSelectLowest$");
where \w- word character
\d – digit
_ Underscore
Then use the test() method of the RegExp class whether the input matches with our pattern defined.
So we can use like this to check/uncheck the checkboxes of a column in a gridview according to its header checkbox state and does not alter the state of any other checkboxes contained in the page.
======Check or uncheck matched checkboxes only=========

0 comments:
Post a Comment