I am using the below code to create a dynamic textbox and their onchange event.Event fired successfully and it doesn't return any value.Please help me to solve this.
txt_box.Attributes.Add("onchange", "loadValues('" + txt_box.ClientID + "')");
function loadValues(controlName) {
alert(controlName);
//control name comes here
var txtValue = document.getElementById(controlName);
//control also return null
if (txtValue.value.length > 0)
{
alert(txtValue.value.length);
}
}
Was just about to answer the same as Ankush Jain, but then none jquery version:
function loadValues(control) {
alert(control.id);
//control name comes here
var txtValue = control.value;
//control also return null
if (txtValue.length > 0) {
alert(txtValue.length);
}
}
txt_box.Attributes.Add("onchange", "loadValues(this);");
try the following
txt_box.Attributes.Add("onchange", "loadValues(this)");
function loadValues(controlName) {
if($(controlName).attr('id').length > 0){
var id= $(controlName).attr('id');
var val= $('#'+id).val();
alert(val);
}
}
Related
I'm trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.
My code is like below:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tTitle"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tEMail"/>
<asp:RegularExpressionValidator runat="server" ControlToValidate="tEMail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit"/>
Javascript
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
{
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
} return true;
}
function WebForm_OnBlur() {
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
}
</script>
The problem is the e-mail field only validates for the regular expression. If I change the order of the validators, it only validates for required expression.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
Yes, this is indeed the problem. To fix it, you can do the following:
In the WebForm_OnBlur function, loop through the validators associated with the control that lost focus (rather than all the validators on the page), and clear the className property only if all the validators are valid:
function WebForm_OnBlur(control) {
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.className = "error";
return;
}
}
control.className = "";
}
In the onblur attribute of the TextBox controls, pass this as the argument to WebForm_OnBlur:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur(this)"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur(this)"/>
In the WebForm_OnSubmit function, call WebForm_OnBlur for each control that has associated validators:
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
for (var i = 0; i < Page_Validators.length; i++) {
var control = document.getElementById(Page_Validators[i].controltovalidate);
if (Page_Validators[i] === control.Validators[0]) // minor optimization
WebForm_OnBlur(control);
}
return false;
}
return true;
}
In addition to #MichaelLiu, You can make your own validators that inherit from the CustomValidator class and alter the rendering of the validators to make them a little easier to work with.
For example:
Validators.cs
Take notice of how we add a property of CssControlErrorClass. We will use this when applying a class with the invalid input in question.
We also set other properties so you don't have to set them everytime, ClientValidationFunction and ValidateEmptyText.
public class RequiredFieldValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public RequiredFieldValidator()
{
ClientValidationFunction = "validators.required";
ValidateEmptyText = true;
}
public string InitialValue
{
get
{
object o = ViewState["InitialValue"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
ViewState["InitialValue"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RequiredFieldValidation validator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null)
{
return true;
}
var result = (!controlValue.Trim().Equals(InitialValue.Trim()));
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if(!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
}
public class RegularExpressionValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public string ValidationExpression
{
get
{
object o = ViewState["ValidationExpression"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
try
{
Regex.IsMatch(String.Empty, value);
}
catch (Exception e)
{
throw new HttpException(string.Format("{0} - {1}", "Validator_bad_regex", value), e);
}
ViewState["ValidationExpression"] = value;
}
}
public RegularExpressionValidator()
{
ClientValidationFunction = "validators.regex";
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-regex", ValidationExpression);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RegularExpressionFieldvalidator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null || controlValue.Trim().Length == 0)
{
return true;
}
try
{
Match m = Regex.Match(controlValue, ValidationExpression);
var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length);
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if (!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
catch
{
return true;
}
}
}
Validators.js
Since in the previous classes we pre-defined the javascript functions, we can add a simple script like so:
var v = window.validators = window.validators || {
errorControlAttributeName: "data-for",
errorClassAttributeName: "data-errorClass",
regexAttributeName: "data-regex",
required: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
input = document.getElementById(controlId);
var isValid = (args.Value !== "");
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
regex: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
regexString = src.getAttribute(v.regexAttributeName),
input = document.getElementById(controlId),
regex = new RegExp(regexString);
var isValid = regex.test(args.Value);
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
/************* Helper functions ***********/
_toggleInputErrorState: function (inputEl, errorClass, isValid) {
if (!isValid) {
if (!v._hasClass(inputEl, errorClass)) {
inputEl.className += " " + errorClass;
}
} else {
if (v._hasClass(inputEl, errorClass)) {
//Not the most performant, but is sure is easiest
inputEl.className = inputEl.className.replace(" " + errorClass, "");
}
}
},
_hasClass: function(el, className) {
return el.className.indexOf(className) != -1 ? true : false;
},
}
Very simple validation library that you can easily extend with things you are actually interesting in.
Default.aspx
After than you can put the controls into your page:
<Validators:RequiredFieldValidator runat="server" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED BRO!"></Validators:RequiredFieldValidator>
<Validators:RegularExpressionValidator runat="server" ValidationExpression="[0-9]" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED RegEx BRO!"></Validators:RegularExpressionValidator>
Is this the best way? Probably not, (these two use the default implementation that is given by Microsoft) there are way smarter people out there than I and I don't work with WebForms much. The biggest benefit I see is that you get some reusable code, using a familiar syntax, that will eventually contain all your validation needs versus messing around with js everytime to get the validation "rules" how you want them.
The issue is resolved by replacing the code snippet below. To correct we must loop through all the validators for a control, then we should decide whether it has to marked with the error class. After this, your code will work as expected.
Replace the loop
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
}
with the below code
for (var j in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[j].controltovalidate);
var IsError = false;
for (var i in control.Validators) {
if (!control.Validators[i].isvalid) {
IsError = true;
}
}
if (IsError)
control.className = "error";
else
control.className = "";
} catch (e) { }
}
I just ran it and this is working excellently :) Try this solution!
you can try Page_ClientValidate() in javascript instead of looping across validator.
I believe this will validate all the validators on the page.
It also takes in parameter which "Validation group name" if you want to validate specific controls bound by particular validation group.
i want to display error message without alert box by using javascript.
i have tried with code.
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname=="") {
document.getElementById("text_uname").innerHTML= "Enter Username"; } }
but it is not working, please give some suggestions
You need to use document.getElementById('<%=txt_uname.ClientID %>') instead of document.getElementById("text_uname")
Complete function
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if (txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').innerHTML = "Enter Username";
}
}
try to cache dom, and set innerHTML
function validatetextbox() {
var inputEl = document.getElementById('<%=txt_uname.ClientID %>'),
txtuname = inputEl.value;
if ( txtuname == "" ) {
inputEl.innerHTML = "Enter Username";
}
}
It seems like you need to show alert in txt_uname .. then you should do like this:
function test(){
var txtuname =document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').value= "Enter Username";
}
}
try this
function test()
{
var row = lnk.parentNode.parentNode;
var txtuname= row.cells[your cell number].childNodes[your node number].innerHTML;
if(txtuname=="")
{
txtuname="enter username";
}
}
I have a dynamically generated list of hyperlinks and i'm using jquery to bind the click events, everything is working fine, just one thing i am unable to do is to changes its text
**this.value = s;**
This is what I was trying to do without any success.
My full code:
$(document).ready(function () {
$('[id*="lnkStatus_"]').bind('click', SaveRequirmentStatus);
});
function SaveRequirmentStatus(event) {
var itemID = $(event.currentTarget).attr('id');
var intProjectId = $('[id$="hdnProjectId"]').val();
var idRequirment = itemID.split('_')[1];
var idRequirementPhase = itemID.split('_')[2];
var idPhaseStatus = $(event.currentTarget).val();
if (intProjectId != '0' && idRequirment != '0' && idRequirementPhase != '0') {
$.getJSON('handler/RequirementLifecycleHandler.ashx? FuncName=SaveRequirment&idRequirment=' + idRequirment + "&idRequirementPhase=" + idRequirementPhase + "&idProject=" + intProjectId + "&idPhaseStatus=" + idPhaseStatus, function (ValueStatus) {
var s = ValueStatus;
alert(this);
this.value = s;
});
}
}
this in the context that you are using it does not refer to the link, so save a reference to it outside of the inner function and use that. Also, a link does not have a value, you can set the text using the jQuery text function.
Changing your code to this should do what you want:
function SaveRequirmentStatus(event) {
var $this = this; // save reference to the clicked link
var itemID=$(event.currentTarget).attr('id');
var intProjectId=$('[id$="hdnProjectId"]').val();
var idRequirment=itemID.split('_')[1];
var idRequirementPhase=itemID.split('_')[2];
var idPhaseStatus = $(event.currentTarget).val();
if (intProjectId != '0' && idRequirment != '0' && idRequirementPhase != '0') {
$.getJSON('handler/RequirementLifecycleHandler.ashx?FuncName=SaveRequirment&idRequirment=' + idRequirment + "&idRequirementPhase=" + idRequirementPhase + "&idProject=" + intProjectId + "&idPhaseStatus=" + idPhaseStatus, function(ValueStatus) {
$this.text(ValueStatus); // set the text of the link to ValueStatus
});
}
}
This should do
$(function() {
$('[id*="lnkStatus_"]').bind('click', SaveRequirmentStatus);
});
function SaveRequirmentStatus(event) {
$(this).text(ValueStatus);
}
Let's assume an aspx page gets multiple querystrings, for example books.aspx?author=Arthor&level=4&year=2004.
I'd like to create a button that clears specific querystring.
For example when clearAuthorBtn is clicked, user should be redirected to books.aspx?level=4&year=2004
How can I make it?
Thank you very much.
ASP.NET, C# something like this pseudo-code should work in your button event handler:
foreach (var key in Request.QueryString)
{
string url = "books.aspx?";
if (key != "author")
{
url = url + Server.UrlEncode(key) + "=" + Server.UrlEncode(Request.QueryString[key]) + "&";
}
Response.Redirect(url);
}
Here is a method that may help. I have not tested this particular implementation, but something like it should suffice (and be fairly robust).
public static string GetQueryStringWithoutKey(HttpRequest request, string keyToRemove) {
// Assert keyToRemove is not null.
if (keyToRemove == null) {
throw new ArgumentNullException("keyToRemove");
}
// If the QueryString has no data, simply return an empty string.
if (request.QueryString.AllKeys.Length == 0) {
return string.Empty;
}
// Reconstruct the QueryString with everything except the existing key/value pair.
StringBuilder queryStringWithoutKey = new StringBuilder();
for (int i = 0; i < request.QueryString.AllKeys.Length; i++) {
// Only append data that is not the given key/value pair.
if (request.QueryString.AllKeys[i] != null &&
request.QueryString.AllKeys[i].ToLower() != keyToRemove.ToLower()) {
queryStringWithoutKey.Append(request.QueryString.AllKeys[i]);
queryStringWithoutKey.Append("=");
queryStringWithoutKey.Append(request.QueryString[i]);
queryStringWithoutKey.Append("&");
}
}
// We might have had a key, but if the only key was Message, then there is no
// data to return for the QueryString.
if (queryStringWithoutKey.Length == 0) {
return string.Empty;
}
// Remove trailing ampersand.
return queryStringWithoutKey.ToString().TrimEnd('&');
}
You can call the above method like this (note that I use HttpContext.Current in case you want to call this outside of an Page or UserControl):
HttpRequest request = HttpContext.Current.Request;
string url = request.ServerVariables["PATH_INFO"];
string queryString = GetQueryStringWithoutKey(request, "author");
if (!string.IsNullOrEmpty(queryString) {
url += "?" + queryString;
}
HttpContext.Current.Response.Redirect(url);
Currently I am working on a web page which will tell user about certain configurations on client machine. Out of this there is also requirement of detecting if Adobe Reader is installed on client machine or not. I am using ASP.NET/C#.
I have looked the following url for the answer
"Check Adobe Reader is installed (C#)?" but the code look into the server registry entires where IIS is installed and not the client machine where browser is running.
Is it possible to detect if Adobe reader is installed on client machine and not the server which is hosting the website?
pls, check the script below, it worked fine for me in IE, FireFox and Chrome
<html>
<body>
<script type="text/javascript">
var found = false;
var info = '';
try
{
acrobat4 = new ActiveXObject('PDF.PdfCtrl.1');
if (acrobat4)
{
found = true;
info = 'v. 4.0';
}
}
catch (e)
{
//???
}
if (!found)
{
try
{
acrobat7 = new ActiveXObject('AcroPDF.PDF.1');
if (acrobat7)
{
found = true;
info = 'v. 7+';
}
}
catch (e)
{
//???
}
if (!found && navigator.plugins && navigator.plugins.length>0)
{
for (var i = 0; i<navigator.plugins.length; i++)
{
if (navigator.plugins[i].name.indexOf('Adobe Acrobat') > -1)
{
found = true;
info = navigator.plugins[i].description + ' (' + navigator.plugins[i].filename + ')';
break;
}
}
}
}
document.write("Acrobat Reader Installed : " + found);
document.write("<br />");
if (found) document.write("Info : " + info);
</script>
</body>
</html>
hope this helps, regards
I used this script and called it on ready function :
Note: i used the alerts here just to know how to use it.
<script type="text/javascript">
$(document).ready(function () {
alert(getAcrobatInfo().browser);
alert(getAcrobatInfo().acrobat === "installed");
alert(getAcrobatInfo().acrobatVersion);
});
var getAcrobatInfo = function () {
var getBrowserName = function () {
return '<%=Session["browser"].ToString()%>';
};
var getActiveXObject = function (name) {
try { return new ActiveXObject(name); } catch (e) { }
};
var getNavigatorPlugin = function (name) {
for (key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name == name) return plugin;
}
};
var getPDFPlugin = function () {
return this.plugin = this.plugin || function () {
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF') || getWebKitPlugin();
}
}();
};
var getWebKitPlugin = function () {
for (var key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name && plugin.name.substring(0, 6) == "WebKit" && (plugin.name.indexOf("pdf") != -1 || plugin.name.indexOf("PDF") != -1)) return plugin;
}
};
var isAcrobatInstalled = function () {
return !!getPDFPlugin();
};
var getAcrobatVersion = function () {
try {
var plugin = getPDFPlugin();
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if (plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch (e) {
return null;
}
}
// The returned object
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
</script>
Also add this code behind:
public void detectBrowser()
{ //Set the Browser session variable
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Session["Browser"] = browser.Browser;
}
Hope it helps.