How to get values from dynamically generated controls in asp.net c#? - c#

I know this is a well asked question and I found some marked as answers but those doesn't solve my problem. Please have a look at my codes..
Method to Display dynamic controls
private void ShowControlsByFormId()
{
List<FormControlsBO> list = new List<FormControlsBO>();
list = new FormControlsDA().FormControls_GetByFormId(Convert.ToInt32(ddlForm.SelectedValue.ToString()));
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
DynamicControl dynamicControl = CommonUtility.GenerateControl(list[i]);
pnlInput.Controls.Add(new LiteralControl("<tr><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControlLiteral);
pnlInput.Controls.Add(new LiteralControl("</td><td></td><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControl);
pnlInput.Controls.Add(new LiteralControl("</td><tr><br/><br/>"));
}
pnlAction.Visible = true;
}
else
{
pnlAction.Visible = false;
}
}
Method to Generate dynamic controls
public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();
LiteralControl literal = new LiteralControl();
switch (bo.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
}
control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;
return dynamicControl;
}
Method to Save data
private void FormRecords_Save()
{
List<FormControlsBO> list = new List<FormControlsBO>();
FormControlsBO bo = new FormControlsBO();
foreach (Control ctl in pnlInput.Controls)
{
CommonUtility.DataFiller(bo, ctl);
list.Add(bo);
}
Boolean result = false;
result = new FormControlsDA().FormRecords_Save(list);
if(result == true)
{
lblMessage.Text = "Form data saved successfully";
}
else
{
lblMessage.Text = "Form data not saved";
}
}
The problem is, when I debug the code, pnlInput.Controls shows Zero count. Please help !!

As I already answered here all dynamic controls should be reinitiated in Page's Init event, as viewstate manager values are set every request. You can check page's lifecycle.
So right now, when you do not create you control in init event, viewstates misses them while it is setting postback data, and when you do try to get values, they are equal to zeros.
Keep in mind, that you have to create the same control types with the same names.

If you have written the code to generate Dynamic Controls and if it is in the page load event use FindControl("IdofControl"); to retrive its value;
For Example,
TextBox txtInstance = (TextBox)FindControl("IdofControl");
string txtvalueinTextBox =txtInstance.Text;
Make sure that the controls are dynamically generated in all page reloads.If the controls generated on the postback is different the viewState may not restore back properly.

Related

Loading data dynamically into the Repeater from code behind file

The question may be a bit long :
I am making an Online Evaluation Portal and there different type of questions in database which needs to be loaded in the web- form. The questions can be Single Answer(radio button) or multi-answer(check box button). So depending upon the type I create the radio button or check box as per requirement and load it in the Repeater during Runtime. The code is as below :
SqlCommand cmd = new SqlCommand("select * from tbl_QuestionAnswer", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer1";
rAnswer1.GroupName = "QAnswer1";
rAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(rAnswer1);
RadioButton rAnswer2 = new RadioButton();
rAnswer2.ID = "rbl_Answer2";
rAnswer2.GroupName = "QAnswer1";
rAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(rAnswer2);
RadioButton rAnswer3 = new RadioButton();
rAnswer3.ID = "rbl_Answer3";
rAnswer3.GroupName = "QAnswer1";
rAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(rAnswer3);
RadioButton rAnswer4 = new RadioButton();
rAnswer4.ID = "rbl_Answer4";
rAnswer4.GroupName = "QAnswer1";
rAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(rAnswer4);
}
else
{
CheckBox cAnswer1 = new CheckBox();
cAnswer1.ID = "chk_Answer1";
cAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(cAnswer1);
CheckBox cAnswer2 = new CheckBox();
cAnswer2.ID = "chk_Answer2";
cAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(cAnswer2);
CheckBox cAnswer3 = new CheckBox();
cAnswer3.ID = "chk_Answer3";
cAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(cAnswer3);
CheckBox cAnswer4 = new CheckBox();
cAnswer4.ID = "chk_Answer4";
cAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(cAnswer4);
}
}
But the problem here is all the answers get loaded in all questions. i.e. from that dr["Answer1"] it takes all the data in the "Answer1" column and then makes a check-box or radio-button. I don't know why that is happening as it should take only onr row at a time and data from that row only.
Also this runs good till 2 questions. After that if I add 3rd question and try to load it, it gives error saying "Multiple controls with the same ID 'rbl_Answer1' were found. FindControl requires that controls have unique IDs.". And this is correct too. So I need a approach to load questions into the web-form dynamically depending on Single answer or multi -asnwer
It's very clear that you may create control with the same id if you have more than one row in your query.
Try to make dynamic field/control and set dynamic ID for those control
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer" + dr["AnswerID1"].ToString();
or something like that...

Dynamic names for panels

I'm working on a program that is supposed to use with multiple users. I'm getting the users from a database. So far so good...
I'm dynamically adding a panel to the form, which would hold some data. I'm using this piece of code to achieve that:
string panel_name = "email_in_" + user_credentials[counter_snel][0];
Panel new_user_panel = new Panel();
new_user_panel.AutoSize = true;
new_user_panel.Dock = System.Windows.Forms.DockStyle.Fill;
new_user_panel.Location = new System.Drawing.Point(0, 0);
new_user_panel.Name = panel_name;
new_user_panel.Visible = false;
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
splitContainer2.panel_name.Controls.Add(new_item);
as you will probably notice, this line of code is not working:
splitContainer2.panel_name.Controls.Add(new_item);
How can I achieve this, so when I want to make panel email_in_1 visible, I can use that, and make email_in_8 not visible?
### EDIT 1 ###
the code now looks like this:
string panel_name = "email_in_" + user_credentials[counter_snel][0];
Panel new_user_panel = new Panel();
new_user_panel.AutoSize = true;
new_user_panel.Dock = System.Windows.Forms.DockStyle.Fill;
new_user_panel.Location = new System.Drawing.Point(0, 0);
new_user_panel.Name = panel_name;
new_user_panel.Visible = true;
user_email_in_panels.Add(new_user_panel);
splitContainer2.Panel1.Controls.Add(new_user_panel);
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
int aantal_panels = 0;
foreach (Panel panel in user_email_in_panels) {
aantal_panels++;
}
int counter_1 = 0;
foreach (Panel panel in user_email_in_panels) {
if(counter_1 == (aantal_panels -1)){
MessageBox.Show("We are here");
panel.Controls.Add(new_item);
splitContainer1.Panel1.Controls.Add(panel);
}
counter_1++;
}
But somehow, i don't see any labels shown in the form... am i missing something? The messsagebox with the text We are Here is shown, so it come's to the add statement....
and i've got an another question besides my first question. My question is, how can i make the counter of the list better?
### Edit for Sean Vaughn
i've updated it to this:
public class MyPanelClass {
public string Name {
get;
set;
}
public bool Visible {
get;
set;
}
public string YourLabelsText {
get;
set;
}
}
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2], user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
Panel base_panel = new Panel(); //this is your base panel, you don't need to add this line of code because Visual Studio will do that for you.
List<MyPanelClass> myPanelList = new List<MyPanelClass>(); //this will keep records of all of your panels.
MyPanelClass panel_name = new MyPanelClass();
panel_name.Name = "email_in_" + user_credentials[counter_snel][0]; ;
panel_name.Visible = true;
panel_name.YourLabelsText = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2], user_credentials[counter_snel][9]);
//Now add the new created panel to the list.
myPanelList.Add(panel_name);
base_panel.Name = myPanelList[counter_snel].Name;
base_panel.Visible = myPanelList[counter_snel].Visible; //You probably don't need this because base_panel will always be visible
new_item.Text = myPanelList[counter_snel].YourLabelsText;
But i still doesn't see anything...
Does it matter that it execudes in an public void??? i don't think so, but it want to elliminate all the possibilities...
Use a List that will keep track of all the panels.
List<Panel> myPanels = new List<Panel>();
Whenever you need to add a panel, do this:
mypanels.Add(yourPanel);
Now, for the other problem, create a function like this:
private void HideAllOtherPanels(List<Panel> panelList, Int index /*the index of the panel you want to show*/)
{
foreach(Panel panel in panelList)
if(panel.Visible) panel.Hide();
panelList[index].Show();
}
I see you are creating a lot of new panels. My advice, don't do that, you're giving a lot of load to the system.
Instead make a class.
public class MyPanelClass
{
public string Name
{
get; set;
}
public bool Visible
{
get; set;
}
public string YourLabelsText
{
get; set;
}
}
After creating the class, create a base_panel on your form that will change it's contents based on the your intentions.
And then, all you need to do is change the panel's content rather than creating a new Panel. Store the other panels data in a List<MyPanelClass>.
So you'll be doing this:
Panel base_panel = new Panel(); //this is your base panel, you don't need to add this line of code because Visual Studio will do that for you.
List<MyPanelClass> myPanelList = new List<MyPanelClass>(); //this will keep records of all of your panels.
MyPanelClass panel_name = new MyClassPanel();
panel_name.Name = "email_in_" + user_credentials[counter_snel][0];;
panel_name.Visible = false;
panel_name.YourLabelsText = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
//Now add the new created panel to the list.
myPanelList.Add(panel_name);
Now whenever you need to activate a stored Panel, just do this:
base_panel.Name = myPanelList[yourPanelsIndex].Name;
base_panel.Visible = myPanelList[yourPanelsIndex].Visible; //You probably don't need this because base_panel will always be visible
yourLabel.Text = myPanelList[yourPanelsIndex].YourLabelsText;
This code is much less bulky on the machine and is easy to handle too.
I'd try something like this to add an item.
var panel = splitContainer2.Controls.FirstOrDefault(p => p is Panel && ((Panel)p).Name == panel_name);
if(panel != nul)
{
panel.Controls.Add(new_item);
}
To hide a particular panel given panel_name:
foreach(var control in splitContainer2.Controls)
{
if(control is Panel)
{
((Panel)control).Visible = ((Panel)control).Name == panel_name;
}
}

How to create dynamic checkbox in asp.net

I am creating an application where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
Put a placeHolder on your form with the ID placeHolder and add the following code to your Page_Load():
CheckBoxList cbList = new CheckBoxList();
for (int i = 0; i < 10; i++)
cbList.Items.Add(new ListItem("Checkbox " + i.ToString(), i.ToString()));
placeHolder.Controls.Add(cbList);
This will add 10 CheckBox objects within your CheckBoxList(cbList).
Use the following code to examine each CheckBox object within the CheckBoxList
foreach(ListItem li in cbList.Items)
{
var value = li.Value;
var text = li.Text;
bool isChecked = li.Selected;
}
The placeholder is used to add the CheckBoxList to the form at runtime, using a placeholder will give you more control over the web page where the CheckBoxList and its items will appear.
Here is an example
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
chkList.ID = "ChkUser";
chkList.AutoPostBack = true;
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
this.Form.Controls.Add(pUser);
At code behind you can create new ASP.NET Controls and you can add these controls to your page. All you need to do is to create new CheckBoxList Object and add ListItems to it. Finally, you need to add your CheckBoxList to your Page.
// Create CheckBoxList
CheckBoxList list= new CheckBoxList();
// Set attributes for CheckBoxList
list.ID = "CheckBoxList1";
list.AutoPostBack = true;
// Create ListItem
ListItem listItem = new ListItem();
// Set attributes for ListItem
listItem .ID = "ListItem1";
// Add ListItem to CheckBoxList
list.Items.Add(listItem );
// Add your new control to page
this.Form.Controls.Add(list);

How to place child controls in a certain order when binding a custom control?

What I'm trying to achieve is a custom calendar where I place events.
I've created a basic custom control which simply lists the events:
namespace MyControls
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public class Calendar : CompositeDataBoundControl
{
protected override Int32 CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
{
Int32 itemCounter = 0;
if (dataSource != null)
{
IEnumerator dataSourceEnumerator = dataSource.GetEnumerator();
while (dataSourceEnumerator.MoveNext())
{
LinkButton eventLink = new LinkButton();
eventLink.Click += new EventHandler(EventLinkClick);
HtmlGenericControl eventContainer = new HtmlGenericControl();
eventContainer.Controls.Add(eventLink);
eventContainer.TagName = "p";
this.Controls.Add(eventContainer);
if (dataBinding)
{
CalendarEvent currentEvent = (CalendarEvent) dataSourceEnumerator.Current;
eventLink.CommandArgument = String.Concat(currentEvent.Name, "ยง", currentEvent.Day.ToBinary());
eventLink.Text = currentEvent.Name;
eventLink.ToolTip = currentEvent.Description;
}
itemCounter++;
}
}
return itemCounter;
}
protected void EventLinkClick(Object sender, EventArgs e)
{
}
}
}
The control works, when I pass it a List<CalendarEvent> it displays every event's LinkButton inside its own <p />, when I click a LinkButton the EventLinkClick method gets called, and after the postback the LinkButtons are still there with their values.
However, I don't need a plain list of the event, I need to place my events inside a calendar, inside the correct day.
I create my calendar like this:
Int32 year = 2011;
Table monthTable = null;
TableRow weekRow = null;
for (DateTime day = new DateTime(year, 1, 1); day.Year == year; day = day.AddDays(1))
{
if (day.Day == 1)
{
HtmlGenericControl monthName = new HtmlGenericControl();
monthName.InnerText = CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(day.Month);
monthName.TagName = "h2";
this.Controls.Add(monthName);
monthTable = new Table();
TableHeaderRow headerRow = new TableHeaderRow();
headerRow.TableSection = TableRowSection.TableHeader;
monthTable.Rows.Add(headerRow);
for (Int32 i = 0; i < 7; i++)
{
TableHeaderCell dayOfWeekCell = new TableHeaderCell();
dayOfWeekCell.Text = CultureInfo.CurrentUICulture.DateTimeFormat.GetShortestDayName((DayOfWeek) i);
headerRow.Cells.Add(dayOfWeekCell);
}
weekRow = new TableRow();
weekRow.TableSection = TableRowSection.TableBody;
for (Int32 i = 0; i < (Int32) day.DayOfWeek; i++)
{
weekRow.Cells.Add(new TableCell());
}
}
if (day.DayOfWeek == DayOfWeek.Sunday && day.Day != 1)
{
monthTable.Rows.Add(weekRow);
weekRow = new TableRow();
weekRow.TableSection = TableRowSection.TableBody;
}
TableCell dayCell = new TableCell();
dayCell.Text = Convert.ToString(day.Day);
weekRow.Cells.Add(dayCell);
if (day.Day == DateTime.DaysInMonth(day.Year, day.Month))
{
for (Int32 i = (Int32) day.DayOfWeek; i < 6; i++)
{
weekRow.Cells.Add(new TableCell());
}
monthTable.Rows.Add(weekRow);
this.Controls.Add(monthTable);
}
}
which yields to something like this:
.
Now, how can I integrate the two things?
What I came up with is casting the dataSource parameter to IEnumerable<CalendarEvents> and after the dayCell.Text = Convert.ToString(day.Day); line I get the events of the day from the IEnumerable<CalendarEvents> through LINQ.
However, this breaks on postback because when the control is recreating itself after a postback the dataSource parameter is full of nulls, so I can't fetch the events of the day, so I can't recreate the controls.
I couldn't find anything on the net about this, and I'm completely stuck.
Am I missing (or messing) something? What should I do to achieve what I'm looking for?
Update #1
As StriplingWarrior suggested I tried to save the dataSource in the ViewState, however I failed dramatically.
What I tried is this: at the beginning of the CreateChildControls method I placed
if (dataBinding)
{
this.ViewState.Add("myDataSource", dataSource);
}
IEnumerable myDataSource = (IEnumerable) this.ViewState["myDataSource"];
and replaced every call to dataSource with myDataSource.
However, when the page post backs this.ViewState["myDataSource"] is null, and I'm back to square one.
I'm starting to regret when I decided to go with a CompositeDataBoundControl... :\
Update #2
I tried to create a new project containing only the custom control, and I rewrote it from scratch, and StriplingWarrior's suggestion worked:
if (dataBinding)
{
this.ViewState.Add("DataSource", dataSource);
}
else
{
dataSource = (IEnumerable) this.ViewState["DataSource"];
}
However, I haven't been able to pinpoit what was causing the this.ViewState["DataSource"] in the original solution.
You're running into ViewState issues. You can either disable viewstate on your control, or write the control in such a way that it saves the information it needs in ViewState, so it doesn't need to rebind to the data source on subsequent postbacks.

Javascript tabs: call event onclick

I got some code I need to change. it is build by others, and not very neat...
There is a javascript tabcontrol, containing 4 tabs, which contains gridviews.
All the 4 gridviews are build during the load of the page, but I want them to load, when you activate the tabs (as it is possible to watch the side, while you don't need the specific gridviews to see)
So, my question is: how to call an event (that loads the gridview) from an javascript tab?
how the tabs are generated: (generated code, I know, horrible)
var obj = 0;
var oid = 0;
var otb = 0;
var myTabs = new Array();
var myTabitems = new Array();
var myTabitem = new Array();
var myTabContent = new Array();
var myLists = new Array();
function showTabContent(tab)
{
tb = tab.obj;
id = tab.nr;
if (myTabs[tb].oid != -1)
{
myTabs[tb].myTabContent[myTabs[tb].oid].style.display = 'none';
myTabs[tb].myTabitem[myTabs[tb].oid].className -= " active";
}
myTabs[tb].myTabContent[id].style.display = 'block';
myTabs[tb].myTabitem[id].className += " active";
myTabs[tb].oid = id;
}
function boTabs()
{
var myBlocks = new Array();
myBlocks = document.getElementsByTagName("div");
var stopit = myBlocks.length;
for (var g = 0; g < stopit; g++)
{
if (myBlocks[g].className == "tabs")
{
myTabs.push(myBlocks[g]);
}
}
var stopit2 = myTabs.length;
for (var i = 0; i < stopit2; i++)
{
myTabs[i].myLists = myTabs[i].getElementsByTagName("ul");
if (myTabs[i].myLists[0].className == "tabs")
{
myTabs[i].myTabitems = myTabs[i].myLists[0].getElementsByTagName("li");
}
var stopit3 = myTabs[i].myTabitems.length;
myTabs[i].obj = i;
myTabs[i].myTabitem = new Array();
myTabs[i].myTabContent = new Array();
for (var j = 0; j < stopit3; j++)
{
myTabs[i].myTabitem.push(myTabs[i].myTabitems[j]);
myTabs[i].myTabitem[j].nr = j; myTabs[i].myTabitem[j].obj = i;
myTabs[i].myTabitem[j].onclick = function() { showTabContent(this); };
}
var myTabDivs = myTabs[i].getElementsByTagName("div");
for (var j = 0; j < myTabDivs.length; j++)
{
if (myTabDivs[j].className == "tabcontent")
{
myTabs[i].myTabContent.push(myTabDivs[j]);
}
}
myTabs[i].myTabitem[0].className += " active";
myTabs[i].myTabContent[0].style.display = 'block';
myTabs[i].oid = 0;
myTabDivs = null;
}
myBlocks = null;
}
onload = boTabs;
I would change it entirely to use JQuery Tabs and JQuery AJAX to load the grids
If you want a JS solution, you have to build the gridview table yourself using JS code... If you want the server to do the work, you need an UpdatePanel, and make use of the client _doPostBack method. If you like this approach, the Ajax Control Toolkit tab container can be configured to postback to the server whenever the tab changes, which you can wrap this control with an update panel, and it looks like everything is being done with JS code. Alternatively, you can also use a web service that binds a gridview and returns the HTML too... not tried that yet, but seen it done.
HTH, if you let me know what option you prefer, I could update accordingly.
I now got the tabcontrol made by JQuery and CSS.
at this moment all 4 gridviews are bound at Page_Load, but, as it takes time to run te sproc's behind the gridview, it takes a few seconds. Therefore I want to load them on tabclick... The UpdatePanel seems the best way...
JQuery:
$(document).ready(function()
{
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function()
{
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});

Categories

Resources