Create button OnClientClick asp net - javascript

I'm creating button from code c#:
Button btnAddCalculation = new Button();
btnAddCalculation.ID = "btnAddCalculation";
btnAddCalculation.Text = "Add count";
btnAddCalculation.SkinID = "middleButton";
btnAddCalculation.Visible = true;
string sPath = String.Format(
"WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
SessionViewstateConstants.CalculationType,
CalcType.New,
Guid.NewGuid(),
oEditedDocument.Id.ToString()
);
// btnAddCalculation.Attributes.Add("onclick", #"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
btnAddCalculation.Click += new EventHandler(btnClick_cl);
btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";
public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
{
return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
}
but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???
Generated HTML:
<input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr‌​433$btnAddCalculatio‌​n"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr43‌​3_btnAddCalculation"
disabled="disabled" class="blue_button" />

For Button being disabled
If the dynamic button is added to a container that is itself disabled, then this dynamic button will also be disabled. To make this sure that button is added properly, use a new container in HTML (e.g. <asp:PlaceHolder>) and add button to that container from codebehind.
Also good to check following :-
When Creating the new button, use CausesValidation = false. This will avoid any RequiredFieldValidator getting fired when this button is clicked. RequiredFieldValidator also stops button from being clicked.
e.g.
Button btnAddCalculation = new Button();
btnAddCalculation.ID = "btnAddCalculation";
btnAddCalculation.Text = "Add count";
btnAddCalculation.SkinID = "middleButton";
btnAddCalculation.Visible = true;
btnAddCalculation.Enabled = true;
btnAddCalculation.CausesValidation = false;

Fix this:
Button btnAddCalculation = new Button();
btnAddCalculation.ID = "btnAddCalculation";
btnAddCalculation.Text = "Add count";
btnAddCalculation.SkinID = "middleButton";
btnAddCalculation.Visible = true;
btnAddCalculation.Enabled = true;
string sPath = String.Format(
"WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
SessionViewstateConstants.CalculationType,
CalcType.New,
Guid.NewGuid(),
oEditedDocument.Id.ToString()
);
// btnAddCalculation.Attributes.Add("onclick", #"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
btnAddCalculation.Click += new EventHandler(btnClick_cl);
btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";
public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
{
return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
}
By default the asp.net server will create the button as disabled unless you specify explicitly otherwise.

The ASP.NET code you provided looks ok; so I suspect the problem is related to a script that is run on the clientside. Maybe the submit-button is disabled because the form contents are not valid yet. In this case your button might be disabled, depending on the selector that is used to identify the submit-button.
To avoid this, change the behavior of the button so that it is rendered as an input of type button instead of submit. You can use the UseSubmitBehavior-property to achieve this:
btnAddCalculation.UseSubmitBehavior = false;

Related

Dynamically added checkbox value doesn't work

I am sending a post request to my database and according to the response, I am dynamically creating new checkboxes in my JSP page. Like this (here getMediums function is a onclick event handler of another component in my JSP page):
function getMediums(str)
{
currentClass = str; // save the current class
<%
String classStart = "<script>document.writeln(str)</script>";
HashMap<String, ArrayList<String> > medSubjects;
if(!tutoringInfoAcademic.containsKey(classStart)){ // first click
medSubjects = new HashMap<>();
tutoringInfoAcademic.put(classStart,medSubjects); // opening a blank map
}
else{ // already selected some medium of this class
medSubjects = tutoringInfoAcademic.get(classStart);
}
%>
// javascript code
var data = {};
data["classStart"] = str;
$.post('PopulateMedium',data,function(responseJson){
if(responseJson!=null){
var td = document.getElementById("mediums");
$(td).empty(); // deletes previous contents
$.each(responseJson,function(key,value){
var temp = value;
console.log(temp); // prints as per expected
var checked = "";
<%
String t = "<script>document.writeln(temp)</script>";
if(medSubjects.containsKey(t)){
// already selected, so check this checkbox
%>
checked = "checked";
<%
}
%>
td.innerHTML += " <input type='checkbox' onclick='medCheckboxOnClick()' name='mediumCheckbox' value=" + temp + " " +checked + "/>";
if(value == 'bm')td.innerHTML += "Bangla medium"
else if(value == 'em')td.innerHTML += "English medium";
else if(value == 'ev')td.innerHTML += "English version";
td.innerHTML += "<br/>";
})
}
});
}
The checkboxes get created as per expected. The onclick function:
function medCheckboxOnClick(){
var t = $(this).attr("value"); // bm, em, ev
console.log("entered into the checkbox onclick function");
if($(this).is(":checked")) {
console.log("checkbox for class "+currentClass+" and medium "+t+" has been checked");
<%
String id = "<script>document.writeln(t)</script>";
String currentClassStart = "<script>document.writeln(currentClass)</script>";
if(tutoringInfoAcademic.containsKey(currentClassStart)){ // redundant check
ArrayList<String> listOfSubjects = tutoringInfoAcademic.get(currentClassStart).get(id);
if(listOfSubjects == null){ // first clicked
listOfSubjects = new ArrayList<>();
tutoringInfoAcademic.get(currentClassStart).put(id,listOfSubjects);
System.out.println(tutoringInfoAcademic.get(currentClassStart));
}
else{ // list of subjects already created. either some subject has been chosen or not
}
}
%>
}
else{
console.log("checkbox for class "+currentClass+" and medium "+t+" has been unchecked");
<%
String ID = "<script>document.writeln(t)</script>";
String curClassStart = "<script>document.writeln(currentClass)</script>";
if(tutoringInfoAcademic.containsKey(currentClassStart)){ // redundant check
tutoringInfoAcademic.get(currentClassStart).remove(ID);
}
%>
}
}
When I click on one of the dynamically created checkboxes, execution enters the the medCheckboxOnClick() function and something like this comes out:
checkbox for class 1 and medium undefined has been unchecked
t remains undefined, though I set the value of the checkbox in the previous function while creating the checkboxes. Moreover, it always consides UNCHECK, no matter whether I have checked or unchecked the checkbox. Here currentClass is a global javascript variable and tutoringInfoAcademic has been set as the session attribute from my controller class. It has been declared like this:
HashMap<String, HashMap<String, ArrayList<String> > > tutoringInfoAcademic = new HashMap<>();
Why does the value of the checkbox remain undefined? And why do I always get the uncheck event caught by the click event handler?
Found the solution by writing
td.innerHTML += " <input type='checkbox' onchange='medCheckboxOnClick(this)' name='mediumCheckbox' value='" + temp + "' " +checked + "/>";
And then the function will have a parameter, which is the checkbox.
function medCheckboxOnClick(cb){
//$('.med').click(function() {
//var t = $(this).attr("value"); // bm, em, ev
var t = $(cb).attr("value");
console.log("entered into the checkbox onclick function");
if($(cb).is(":checked")) {
//
}
else{
//
}

Dynamically generated html, document.getElementByID returns null

I am generating an html table dynamically in my code behind file
protected void PopulateMemberTable()
{
var guid = "";
string[] selectedColumns = new[] { "MEMBID", "MEMBER_NAME", "BIRTH", "IPA", "HPNAME" };
if (Session["guid"] != null)
guid = Session["guid"].ToString();
StringBuilder html = new StringBuilder();
DataTable dt = MemberSearch(guid, membFirst.Text.ToString(), membLast.Text.ToString(), membDob.Text.ToString(), membId.Text.ToString());
if (dt != null)
{
DataTable new_dt = new DataView(dt).ToTable(false, selectedColumns);
html.Append("<table class='table table-hover data-table'>");
html.Append("<thead>");
html.Append("<tr>");
foreach (DataColumn column in new_dt.Columns)
{
html.Append("<th>");
switch(column.ColumnName.ToString())
{
case "MEMBID":
html.Append("Member ID");
break;
case "MEMBER_NAME":
html.Append("Member Name");
break;
case "BIRTH":
html.Append("DOB");
break;
case "IPA":
html.Append("IPA");
break;
case "HPNAME":
html.Append("Health Plan");
break;
}
html.Append("</th>");
}
//btn column (no header)
html.Append("<th></th>");
html.Append("</tr>");
html.Append("</thead>");
html.Append("<tbody>");
var counter = 0;
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
}
else
html.Append("<div class='alert alert-danger' role='alert'>No Members Found</div>");
membTable.Controls.Add(new Literal { Text = html.ToString() });
}
The table is generated just fine, but now I am trying to call some server side code when a row is clicked
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
I attempted to accomplish this task by placing a hidden <asp:Button/> in each row and then adding a corresponding onclick attribute to each <tr> tag
This is how the generated html looks like in the dev console
However when I attempt to click the row I get the following error message
I am having a hard time understanding what exactly I'm doing wrong. I'd appreciate some input, or possibly even an alternative approach.
You can use jquery and use the delegation model to handle click on dynamic elements. if for example you have some html like
<div id="dynamicname'></div>
then use
the jquery code snippet
$(document).on('click','#dynamicname',function(){
//handle your event here
});
dynamic html should always be handled by delegation model. And you can use
var dynamic_name="#"+getYourDynamicRowName;//variable for dynamic id's of dynamic html element
$(document).on('click',dynamic_name,function(){
//handle your event here
});
As per my experience we can not use asp tag while you are creating dynamic HTML.
If you see your code of dev console you can see that controls are not rendered properly..rendered with asp tag..
To achieve it you can use javascript/Jquery to call server side function.
<input type="button" ID="btn" runat="server" onclick="fn();" />
And in your javascript:
fn = function(){
__doPostBack("<%=btn.ClientID%>", "");
}
And in your code:
`
protected override void btnEvent(IPostBackEventHandler source, string eventArgument)
{
//call the button event
//base.btnEvent(source, eventArgument);
if (source == btn)
{
//do some logic
}
}
After figuring out that passing an <asp:button/> as a string wasn't going to work, I took an alternative approach.
In populateMemberTable()I added an href attribute to the first column in each row
var href = true;
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
if (href)
{
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");
html.Append(row[column.ColumnName]);
html.Append("</a></td>");
}
else
{
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
}
And then I saved the membId as a session variable in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
//save guid (http://url.com?guid=xxxxxx) as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
{
Session["membid"] = membId;
}
}
It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!

Request.Form.FindAllKeys Not Working In IE8

I am creating textboxes on my page client side like so..
var _text = document.createElement("input");
_text.setAttribute("type", "text");
_text.setAttribute("id", "txtAsName" + num);
_text.setAttribute("name", "txtAsName" + num);
In the server side code I retrieve the ids of any textboxes on the form (you could add txtAsName1, txtAsName2, txtAsName3 and then remove txtAsName2 all client side so its important in my case to grab any textboxes on left on the form during a postback)
I am getting the ids of the remaining textboxes on the server side using this:
string[] allFormKeys = Request.Form.AllKeys;
foreach (string key in allFormKeys)
{
Response.Write("Key Name: " +key + "<br/>");
if (key.StartsWith("txtAsName"))
{
txtBoxes.Add(key);
}
}
In firefox this works fine but in IE8 Request.Form.AllKeys returns no textboxes! I can see this via the Response.Write and in firefox I get the textboxes.
I checked if maybe there is 2 form tags in the html but that isnt the case
Is it possible that you are forgetting to append the newly created element to your form?
<script>
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("name", "testing123");
input1.setAttribute("value", "i like cake");
document.getElementById("formid").appendChild(input1);
</script>
You don't say in your question what you add the text input elements to. I used your code, made sure I was adding the text input fields as children somewhere inside the form element, and I'm definitely seeing them get posted back to the server:
<div id="testDiv"></div>
<br />
<asp:Label ID="Label1" runat="server" />
<asp:Button runat="server" />
<script type="text/javascript">
var num = 0;
var _text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
num++;
_text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
num++;
_text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
</script>
and
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.AllKeys.Length > 0)
{
string keys = string.Join(", ", Request.Form.AllKeys);
Label1.Text = string.Format("Found {0} keys: {1}", Request.Form.AllKeys.Length, keys);
}
else
{
Label1.Text = "Form.AllKeys.Length == 0";
}
}
When I run this and then click the button, the label shows:
Found 6 keys: __VIEWSTATE, __EVENTVALIDATION, txtAsName0, txtAsName1, txtAsName2, ctl00$MainContent$ctl00
I'm using IE8.
Look into the page html generated. There might be a possibility of improper html markup been generated from server. i.e., some html tags have not been closed properly with close tag.

SPGridView Field - javascript:window.open issue

I have an issue where in the SPGridView if I add a hyperlink field or anything, it seems like the javascript:window.open does not work. It does not show as a hyperlink.
Any advice?
I was able to resolve this one myself:
BoundField colCaseTitle = new BoundField();
colCaseTitle.ItemStyle.Width = Unit.Pixel(200);
colCaseTitle.DataField = "CaseTitleModal";
colCaseTitle.HeaderText = "Title";
colCaseTitle.SortExpression = "CaseTitle";
**colCaseTitle.HtmlEncode = false;**
dataFilterList += ",";
this.spGridView.Columns.Add(colCaseTitle);
Also added this to my class that I am binding with:
return "" + CaseTitle + "";

C# using textbox as "post it" / "sticky memo" client side event

I want a textbox to act like a "post it" or "Sticky memo" just like widget Igoogle or Windows 7 widget.
The idea:
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
Every time that user types into the textbox it calls Javascript to save the text into cookies.
Could somebody give me a hint?
This is somewhat quick and dirty but will get you going.
There's plenty of setCookie/getCookie JS snippets around the web. I used these:
http://www.dotnetspark.com/kb/1480-use-cookies-javascript-getcookie-setcookie.aspx
Teh code now:
<input type="text" id="txtMemo" />
<script type="text/javascript">
function setCookie(CookieName, CookieVal, CookieExp, CookiePath, CookieDomain, CookieSecure)
{
var CookieText = escape(CookieName) + '=' + escape(CookieVal); //escape() : Encodes the String
CookieText += (CookieExp ? '; EXPIRES=' + CookieExp.toGMTString() : '');
CookieText += (CookiePath ? '; PATH=' + CookiePath : '');
CookieText += (CookieDomain ? '; DOMAIN=' + CookieDomain : '');
CookieText += (CookieSecure ? '; SECURE' : '');
document.cookie = CookieText;
}
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
function getCookie(CookieName)
{
var CookieVal = null;
if(document.cookie) //only if exists
{
var arr = document.cookie.split((escape(CookieName) + '='));
if(arr.length >= 2)
{
var arr2 = arr[1].split(';');
CookieVal = unescape(arr2[0]); //unescape() : Decodes the String
}
}
return CookieVal;
}
var memoCookieName = "txtMemo_value";
var memoElementId = "txtMemo";
var memoElement = document.getElementById(memoElementId);
memoElement.value=getCookie(memoCookieName);
memoElement.onkeyup = function() {
setCookie(memoCookieName,this.value, new Date(new Date().getTime()+1000*60*60*24*30));
};
</script>
This will work with plain HTML. In your case with ASP.NET markup and controls the ID property has a different meaning, so you need to make your JS aware of the actual client ID. This way for example:
(...)
var memoCookieName = "txtMemo_value";
var memoElementId = "<%= TextBox1.ClientID %>";
var memoElement = document.getElementById(memoElementId);
(...)
Of course. Play with "change" event:
http://www.w3schools.com/jsref/event_onchange.asp
It's just about using this event and update some cookie that you previously created with JavaScript too.

Categories

Resources