im using javascript like
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
and inside the update panel i have code like
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click"
OnClientClick="javascript:return TestCheckBox();" Text="Save" />
when i run the page and click the button then no more further processing just button has been click nothing happan......
Try this:
function TestCheckBox()
{
var TargetBaseControl = null;
if(TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>')){
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
}
alert('Select at least one checkbox!');
return false;
}
look at the source of your page once it is in a browser.
see what happens with the OnClientClick assignment.
does it get rewritten/re-routed ?
it should be pretty clear at that point.
you can also step through with tools such as Firebug in firefox, IE8 developer tools, chrome developer tools, or visual studio
Related
I have javascript function when a control value is changed i am firing a javascript now i wanted to do from c# code.When a value to a control is assigned i wanted it to fire the javascript .Please Help !!.
function AddSelectedUser(sender, eventArgs) {
var dataItem = eventArgs.get_DataItem();
if (dataItem != null) {
// get the selected values
var subscribedUserId = parseInt(eventArgs.get_Value());
var subscribedUserText = eventArgs.get_Text();
var recipientType = dataItem.get_attributes().getAttribute("RecipientType");
//Check if the selected user or group already exists in the selected list
var isExisting = false;
var JSONString = $get(hdnSelectedUsersJsonId).value;
var selectedUserColl = new Array();
if (JSONString != "") {
selectedUserColl = Sys.Serialization.JavaScriptSerializer.deserialize(JSONString);
}
for (j = 0; j < selectedUserColl.length; j++) {
if (selectedUserColl[j].DisplayID == subscribedUserId && selectedUserColl[j].RecipientType == recipientType) {
isExisting = true;
break;
}
}
if (isExisting == false) {
//Add the selected user or group.
var emptyRecipient = new Object();
emptyRecipient.DisplayID = subscribedUserId;
emptyRecipient.DisplayName = subscribedUserText;
emptyRecipient.RecipientType = recipientType;
selectedUserColl.push(emptyRecipient);
$get(hdnSelectedUsersJsonId).value = Sys.Serialization.JavaScriptSerializer.serialize(selectedUserColl);
ConstructTable(false);
}
sender.resetData();
var divScroll = $get('selectedUsersDiv');
divScroll.scrollTop = divScroll.scrollHeight;
}
}
<tele:autocomplete runat="server" pickervisible="false" id="SubscribedUsers" height="100px"
width="250px" dropdownwidth="248px" cssclass="susbscribedUser" pickertooltip="Select Users or Notification Groups"
providertype="InstantNotificationUsersProvider" matchingtype="Contains" controlbehavior="RestrictedToDropdown"
onclientsidecomponentchanged="AddSelectedUser" AutoPostBack="true" />
If you just want to call this function from c# then use ScriptManager.RegisterStartupScript() method.
It's easy just read this method properly and call you function.
As going through the site i got how to access the model in javascript and how to loop it in javascript.
i am using text tag to access the item in a model. when i use i am not able to add break.
#foreach (var item in Model.ArrayDetails)
{
var checklower = false;
var checkUpper = false;
var loopentered = false;
<text>
if(#item.Id ==1)
{
if(#item.LowerBound <= obj.value)
{
loopentered=true;
checklower=true;
}
if(loopentered)
{
alert(#item.UpperBound <= obj.value);
if(#item.UpperBound <= obj.value)
{
checkUpper = true;
}
}
if(checkUpper && checklower)
{
***// here i want to add break statement(if i add javascript wont work)***
}
}
</text>
}
Can some one suggest me how can solve this.
Don't write this soup. JSON serialize your model into a javascript variable and use this javascript variable to write your javascript code. Right now you have a terrible mixture of server side and client side code.
Here's what I mean in practice:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
// This here is PURE javascript, it could (AND IT SHOULD) go into
// a separate javascript file containing this logic to which you could
// simply pass the items variable
for (var i = 0; i < items.length; i++) {
var item = items[i];
var checklower = false;
var checkUpper = false;
var loopentered = false;
if (item.Id == 1) {
if (item.LowerBound <= obj.value) {
loopentered = true;
checklower = true;
}
if (loopentered) {
alert(item.UpperBound <= obj.value);
if(item.UpperBound <= obj.value) {
checkUpper = true;
}
}
if (checkUpper && checklower) {
break;
}
}
}
</script>
and after moving the javascript into a separate file your view will simply become:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
myFunctionDefinedIntoASeparateJavaScriptFile(items);
</script>
I am working in C#.Net. i am having an asp button..
<asp:Button ID="btnSubmitData" ToolTip="Show" runat="server" Text="SHOW" CausesValidation="false"
OnClientClick="return FindSelectedItems();" OnClick="btnShow_Click" />
The function called in OnClientClick is,
function FindSelectedItems() {
var sender = document.getElementById('lstMultipleValues');
var cblstTable = document.getElementById(sender.id);
var checkBoxPrefix = sender.id + "_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";
var total = 0;
for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked) {
total += 1;
if (selectedText == "")
selectedText = document.getElementById
(checkBoxPrefix + i).parentNode.innerText;
else
selectedText = selectedText + "," +
document.getElementById(checkBoxPrefix + i).parentNode.innerText;
}
}
var hifMet1 = document.getElementById('<%=hifMet1.ClientID%>');
hifMet1.value = selectedText;
if (total == 0) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Atleast one metric should be selected.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else if (total > 2) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Only two metrics can be compared.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else {
return true;
}
}
Once i click the SHOW Button, i need to do a validation to check at least one checkbox should get checked in checkbox list. That alert message i am getting (i.e) "Atleast one metric should be selected". But after this part, the page gets reloaded.
I want to avoid the page refresh at this point. What should i do here.?
One way is to hook your validation function into the proper ASP .Net validation lifecycle by using a CustomValidator control and a client validation function.
With a few minor changes you can turn your JavaScript code into a client validation function.
Full example here.
Relevant Snippets
<script language="javascript">
function ClientValidate(source, arguments)
{
// Your code would go here, and set the IsValid property of arguments instead
// of returning true/false
if (arguments.Value % 2 == 0 ){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
Client validation should always be double-checked with server validation; using a CustomValidator with both client/server validation functions is a good way to accomplish this.
Remove script
else {
return true;
}
part from script and call function like this
OnClientClick="javascript:return FindSelectedItems();"
This work for me.
How do I reset an asp.net validation control via JavaScript? The current code sample clears the error message text but does not reset the validation control for the next form submission.
var cv= document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
Update:
Here is the full code sample of the form. I can not seem to get the validation controls fire off on another form submission:
function ClearData() {
var cv = document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
}
<html>
<form>
<asp:TextBox id="MyTextControl" runat="server" />
<asp:CustomValidator ID="MyValidationContorl" runat="server" />
<input type="button" onclick="javascript:ClearCCData(); return false;" runat="server" />
</form>
</html>
Page validation is fired every time you do a post, what appears to be the problem is that you are clearing the validator content cv.innerHTML = '';, this way your validator message is lost forever and you'll think validation is not firing again.
and for #Glennular answer, the code does not handle the validator Display property, if its set to Dynamic the validator will be toggled using validator.style.display, but if its set to None or Inline then validator.style.visibility property will be used instead.
Its better to use asp.net ValidatorUpdateDisplay instead,
<script type="text/javascript">
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
</script>
Update : Reset Validation Summaries
<script type="text/javascript">
function Page_ValidationSummariesReset(){
if (typeof(Page_ValidationSummaries) == "undefined")
return;
for (var i = 0; i < Page_ValidationSummaries.length; i++)
Page_ValidationSummaries[i].style.display = "none";
}
</script>
This one resets all validators in all validation groups.
<script type="text/javascript">
Page_ClientValidate('');
</script>
Try the following chunk of code :
$("#<%= txtUserSettingsEmailRequiredValidator.ClientID %>").css("display", "none");
I hope this will work as it worked for me. :)
Here's code to reset all validators
function CleanForm() {
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
Page_Validators[i].style.visibility = 'hidden';
}
return false;
}
or a single one:
document.getElementById("<%= MyValidationContorl.ClientID %>").style.visibility
= 'hidden';
Using the Page_Validators[i].style.visibility = 'hidden';
Don't work for me so I use this line of code instead: Page_Validators[i].enabled = false;
if (sFirstName == "" && sLastName == "")
{
alert('Reminder: Please first enter student ID to search for the student information before filling out the rest of the form field values');
//Disable all require field validation coontrol on the form so the user could continue to use the Lookup student function.
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = false;
}
return false;
}
else
{
alert('Student Name = ' + sFirstName + ' ' + sLastName);
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = true;
}
return true;
}
How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.
I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!)
<form id="form1" runat="server">
<asp:TextBox ID="txtOne" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server"
ControlToValidate="txtOne" Text="SomeText 1" />
<asp:TextBox ID="txtTwo" runat="server" />
<asp:RequiredFieldValidator ID="rfv2" runat="server"
ControlToValidate="txtTwo" Text="SomeText 2" />
<asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();"
Text="Click" CausesValidation="true" />
</form>
<script type="text/javascript">
function BtnClick() {
//var v1 = "#<%= rfv.ClientID %>";
//var v2 = "#<%= rfv2.ClientID %>";
var val = Page_ClientValidate();
if (!val) {
var i = 0;
for (; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate)
.css("background-color", "red");
}
}
}
return val;
}
</script>
You could use the following script:
<script>
$(function(){
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
if (!val.isvalid) {
$("#" + val.controltovalidate).css("border", "2px solid red");
}
originalValidatorUpdateDisplay(val);
}
}
});
</script>
This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.
Hope this helps,
I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.
Some time ago I spend a few hours on it and since then I have been using some custom js magic to accomplish this.
In fact is quite simple and in the way that ASP.NET validation works. The basic idea is add a css class to attach a javascript event on each control you want quick visual feedback.
<script type="text/javascript" language="javascript">
/* Color ASP NET validation */
function validateColor(obj) {
var valid = obj.Validators;
var isValid = true;
for (i in valid)
if (!valid[i].isvalid)
isValid = false;
if (!isValid)
$(obj).addClass('novalid', 1000);
else
$(obj).removeClass('novalid', 1000);
}
$(document).ready(function() {
$(".validateColor").change(function() {validateColor(this);});
});
</script>
For instance, that will be the code to add on an ASP.Net textbox control. Yes, you can put as many as you want and it will only imply add a CssClass value.
<asp:TextBox ID="txtBxEmail" runat="server" CssClass="validateColor" />
What it does is trigger ASP.Net client side validation when there is a change on working control and apply a css class if it's not valid. So to customize visualization you can rely on css.
.novalid {
border: 2px solid #D00000;
}
It's not perfect but almost :) and at least your code won't suffer from extra stuff. And
the best, works with all kind of Asp.Net validators, event custom ones.
I haven't seen something like this googling so I wan't to share my trick with you. Hope it helps.
extra stuff on server side:
After some time using this I also add this ".novalid" css class from code behind when need some particular validation on things that perhaps could be only checked on server side this way:
Page.Validate();
if (!requiredFecha.IsValid || !CustomValidateFecha.IsValid)
txtFecha.CssClass = "validateColor novalid";
else
txtFecha.CssClass = "validateColor";
Here is my solution.
Advantages over other solutions:
Integrates seamlessly with ASP.NET - NO changes required to code. Just call the method on page load in a master page.
Automatically changes the CSS class when the text box or control changes
Disadvantages:
Uses some internal features of ASP.NET JavaScript code
Tested only on ASP.NET 4.0
HOW TO USE:
Requires JQuery
Call the "Validation_Load" function when the page loads
Declare a "control_validation_error" CSS class
function Validation_Load() {
if (typeof (Page_Validators) != "object") {
return;
}
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var control = $("#" + val.controltovalidate);
if (control.length > 0) {
var tagName = control[0].tagName;
if (tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT") {
// Validate sub controls
}
else {
// Validate the control
control.change(function () {
var validators = this.Validators;
if (typeof (validators) == "object") {
var isvalid = true;
for (var k = 0; k < validators.length; k++) {
var val = validators[k];
if (val.isvalid != true) {
isvalid = false;
break;
}
}
if (isvalid == true) {
// Clear the error
$(this).removeClass("control_validation_error");
}
else {
// Show the error
$(this).addClass("control_validation_error");
}
}
});
}
}
}
}
Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)
const string CSSCLASS = " error";
protected static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList<Control> ctls = new LinkedList<Control>();
while ( ctl != null )
{
if ( ctl.ID == id ) return ctl;
foreach ( Control child in ctl.Controls )
{
if ( child.ID == id ) return child;
if ( child.HasControls() ) ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Add css classes to invalid items
if ( Page.IsPostBack && !Page.IsValid )
{
foreach ( BaseValidator item in Page.Validators )
{
var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
if ( !item.IsValid ) ctrltoVal.CssClass += " N";
else ctrltoVal.CssClass.Replace(" N", "");
}
}
}
Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.