I am new to JS. can u find me the problem and suggest thereby?? Js client side validation is not called. I have server side validation too. by clicking the button only the server side validation is being called. can u guys help?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Users.aspx.cs" Inherits="JSApp.Users" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JsApp</title>
<script type="text/javascript">
function ValidatingForm() {
var b = true;
if (document.getElementById("FnTextBox").valueOf == "") {
document.getElementById("Label4").innerText = "beshi Required";
b = false;
} else {
document.getElementById("Label4").innerText = "";
}
if (document.getElementById("LnTextBox").valueOf == "") {
document.getElementById("Label5").innerText = "koravabe required";
b = false;
} else {
document.getElementById("Label5").innerText = "";
}
if (document.getElementById("EmailTextBox").valueOf == "") {
document.getElementById("Label6").innerText = "ajeeb vabe required";
b = false;
} else {
document.getElementById("Label6").innerText = "";
}
return b;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="FN"></asp:Label>
<asp:TextBox ID="FnTextBox" runat="server"></asp:TextBox>
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="LN"></asp:Label>
<asp:TextBox ID="LnTextBox" runat="server"></asp:TextBox>
<asp:Label ID="Label5" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Email"></asp:Label>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:Label ID="Label6" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="sendButton" runat="server" OnClick="sendButton_Click" OnClientClick="return ValidatingForm()" Text="Send" />
</div>
</form>
</body>
</html>
aspx.cs:server side
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace JSApp
{
public partial class Users : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sendButton_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SaveData();
}
}
private void SaveData()
{
string cs = ConfigurationManager.ConnectionStrings["SampleConnection"].ConnectionString;
SqlConnection connection=new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("spInsertUsers",connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter fnParameter=new SqlParameter("#fn",FnTextBox.Text);
SqlParameter lnParameter=new SqlParameter("#ln",LnTextBox.Text);
SqlParameter emailParameter=new SqlParameter("#email",EmailTextBox.Text);
cmd.Parameters.Add(fnParameter);
cmd.Parameters.Add(lnParameter);
cmd.Parameters.Add(emailParameter);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
private bool ValidateForm()
{
bool b = true;
if (string.IsNullOrEmpty(FnTextBox.Text))
{
b = false;
Label4.Text = "Required";
}
else
{
Label4.Text = string.Empty;
}
if (string.IsNullOrEmpty(LnTextBox.Text))
{
b = false;
Label5.Text = "Required";
}
else
{
Label5.Text = "";
}
if (string.IsNullOrEmpty(EmailTextBox.Text))
{
b = false;
Label6.Text = "Required";
}
else
{
Label6.Text = "";
}
return b;
}
}
}
Try change your button click from:
<asp:Button ID="sendButton" runat="server" OnClick="sendButton_Click" OnClientClick="return ValidatingForm()" Text="Send" />
to:
<asp:Button ID="sendButton" runat="server" OnClick="sendButton_Click" OnClientClick="return ValidatingForm" Text="Send" />
See same issue here:
http://forums.asp.net/t/1069601.aspx?I+want+to+use+onsubmit+asp+net+wont+let+me+
That looks more or less correct. I would try the following:
Add a semicolon to your OnClientClick handler - i.e. "OnClientClick="return ValidatingForm();"
Put a javascript alert inside ValidatingForm (to ensure that it's actually called)
Check your comparison logic, maybe instead of: document.getElementById("FnTextBox").valueOf == ""
how about trying:
document.getElementById("FnTextBox").value.length == 0
innerscript attribute does not have cross browser compatibility. using textContent had solved the issue. when i use innerscript it runs ok in IE and Chrome but does not run in Firefox. that matter i posted as the problem.
Related
I daynamically create options of select in javascript, and click a asp:Button to submit the added options. but i can't get that from ListBox. pls help me!!
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Hello.aspx.cs" Inherits="BeyondInfo.Hello" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Welcome to My First ASP.NET</title>
<script type="text/javascript">
function add() {
var count = document.getElementById("count");
if (count.value == "") {
count.value = 1;
}
count.value = parseInt(count.value) + 1;
var num = count.value;
var listBox2 = document.getElementById("ListBox2");
var optn = document.createElement("OPTION");
optn.value = num;
optn.text = num + "_add";
listBox2.options.add(optn);
}
</script>
</head>
<link href="Common.css" rel="stylesheet" />
<body>
<form id="form1" runat="server">
<div style="height: 277px">
<asp:ListBox ID="ListBox2" runat="server">
<asp:ListItem>b1222222222222222222222222222</asp:ListItem>
<asp:ListItem>b2</asp:ListItem>
<asp:ListItem>b3</asp:ListItem>
<asp:ListItem>b4</asp:ListItem>
</asp:ListBox>
<input id="count" type="hidden" />
<input id="btnAdd" type="button" value="ADD" onclick="add()"/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
</body>
</html>
</p>
Hello.aspx.cs
public partial class Hello : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string sel = "";
foreach (ListItem item in ListBox2.Items) {
sel +=item.Text + ",";
}
Label1.Text = sel;
}
}
Try looking at this post answer by NC01. You may be able to achieve what you want by doing something similar.
Basically they store the added fields in a hidden field so they are accessible server side.
I believe that your problem is that when you add an item to a DropDownList client-side (using JavaScript) that when a PostBack occurs, the item will disappear. The only way around this is to add a hidden server-control to the page and when adding the item client-side, add it to the hidden server-control also, so that when a PostBack occurs you can also add it server-side.
Here's an example.
https://forums.asp.net/t/1287204.aspx?How+to+add+the+values+to+listbox+control+using+javascript
aspx file:
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" runat="server">
<asp:listitem value="1">Item 1</asp:listitem>
<asp:listitem value="2">Item 2</asp:listitem>
<asp:listitem value="3">Item 3</asp:listitem>
<asp:listitem value="4">Item 4</asp:listitem>
<asp:listitem value="5">Item 5</asp:listitem>
<asp:listitem value="6">Item 6</asp:listitem>
</asp:DropDownList>
<input id="DropDownList1NewItems" type="hidden" name="DropDownList1NewItems" runat="server">
<input type="button" onclick="addItem();" value="Add Item">
</form>
<script type="text/javascript">
<!--
function addItem()
{
// Add the item here...
var ddlRef = document.getElementById('<%= DropDownList1.ClientID %>');
var newOption = window.document.createElement('OPTION');
newOption.text = 'SomeNewItem';
newOption.value = 'SomeNewItem';
ddlRef.options.add(newOption);
var hiddenElementRef = document.getElementById('<%= DropDownList1NewItems.ClientID %>');
if ( hiddenElementRef.value.length > 0 )
hiddenElementRef.value += ';';
hiddenElementRef.value += 'SomeNewItem';
}
// -->
</script>
aspx.cs file:
private void Page_Load(object sender, System.EventArgs e)
{
if ( this.IsPostBack )
{
if ( DropDownList1NewItems.Value.Length > 0 )
{
string [] newItemsArray = DropDownList1NewItems.Value.Split(';');
for (int i=0; i<newItemsArray.Length; i++)
{
string newItem = newItemsArray[i];
DropDownList1.Items.Add(new ListItem(newItem, newItem));
}
DropDownList1NewItems.Value = string.Empty;
}
}
}
I am validating some .net textboxes in javascript on focusout via regular expression:
ValidationExpression="[0-9]+(\.[0-9][0-9]?)?"
for all text boxes.
If isValidate, button enabled = true else button enabled = false
but my code doesn't work:
<dx:ASPxTextBox ID="tbxAcPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="tbxMpPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementsById("btApply");
t.disabled = true;
this.focus();
}
}
If you use server control you need to use ctl.ClientID
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementById("<%= btApply.ClientID %>");
t.disabled = true;
this.focus
}
}
I have issue to disable/enable validators for newly add row to gridview which is in Update panel, If I remove Update panel then it's worked perfect, and If I add Update panel then it stops working. I have created sample page.
Default.aspx.
<head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); $('[class*="onoff"] select').change(function () { adjustValidators($('option:selected', this)[0]); }); }); </script></head>
<ajax:ToolkitScriptManager runat="server" ID="RadScriptManager1" AsyncPostBackTimeout="18000"> </ajax:ToolkitScriptManager><asp:MultiView ID="MultiView1" runat="server"> <asp:View ID="group_Group1" runat="server"> <div class="group group1"> <asp:Button ID="btnNext0_top" runat="server" Text="Next >>" OnClick="btnNext_Click" ValidationGroup="surveyValidate0" /> <asp:UpdatePanel runat="server" ID="UPNew" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView runat="server" ID="repeatregion_RRSectionSS" RegionName="RRSectionSS" AutoGenerateColumns="False" GridLines="None" CellSpacing="-1" CssClass="rrsectionss"> <Columns> <asp:TemplateField> <ItemTemplate> <div id="wrapper_ONOFF" runat="server" class="wrapper onoff"> <div class='statement onoff' id="statement_ONOFF" runat="server"> Required Validator :</div> <div class='question onoff' id="questionlayer_ONOFF" runat="server"> <asp:DropDownList runat="server" ID="question_ONOFF" ValidationGroup="surveyValidate0" Data='<%# Eval("ONOFF") %>' Val='<%# Eval("ONOFF_selectedValue") %>'> <asp:ListItem Text="Off" Value="-1"></asp:ListItem> <asp:ListItem Value="1" Text="On"></asp:ListItem> </asp:DropDownList> </div> </div> <div id="wrapper_testsssss" runat="server" class="wrapper testsssss"> <div class='statement testsssss' id="statement_testsssss" runat="server"> Sample Text </div> <div class='question testsssss' id="questionlayer_testsssss" runat="server"> <asp:TextBox runat="server" ID="question_testsssss" type="shortans" Columns='40' ValidationGroup="surveyValidate0" Text='<%# Common.DecodeXML(Eval("testsssss")) %>'></asp:TextBox> <asp:RequiredFieldValidator ID="rfv_question_testsssss" runat="server" ValidationGroup="surveyValidate0" SetFocusOnError="true" EnableClientScript="true" ControlToValidate="question_testsssss" Display="Dynamic" Text="**" ErrorMessage="**" /> </div> </div> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button runat="server" ID="btnAddClick" Text="Add Section" OnClick="btn_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </asp:View> <asp:View ID="group_Group2" runat="server"> <div class="group group2"> <asp:Button ID="btnPrevious1_top" runat="server" Text="<< Prev" OnClick="btnPrevious_Click" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="surveyValidate1" /> </div> </asp:View> </asp:MultiView>
<script type="text/javascript"> function pageLoad(sender, args) { if (args.get_isPartialLoad()) { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); } } function adjustValidators(ctrl) { var id = ctrl.parentNode.id.replace('_question', '_rfv_question').replace('ONOFF', 'testsssss') // alert(ctrl.value); if (ctrl.value == -1) { ValidatorEnable(eval(id), false) } else { ValidatorEnable(eval(id), true) } } </script>
Default.aspx.cs.
protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = (MultiView1.ActiveViewIndex == -1) ? 0 : MultiView1.ActiveViewIndex;
DataTable objData =new DataTable();
if (ViewState["data"] != null)
{
objData = (DataTable)ViewState["data"];
}
else
{
objData = new DataTable();
objData.Columns.Add("testsssss");
objData.Columns.Add("ONOFF");
objData.Columns.Add("ONOFF_selectedValue");
objData.Rows.Add(objData.NewRow());
ViewState["data"] = objData;
}
if (!IsPostBack)
{
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex += 1;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex -= 1;
}
protected void btn_Click(object sender, EventArgs e)
{
DataTable objData = (DataTable)ViewState["data"];
objData.Rows.Add(objData.NewRow());
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
ViewState["data"] = objData;
}
when Click on add then item get added to gridview but validators are not disabled.
Thanks and Regards
Sadiq Modan
After some research and trickery I found the solution: replace eval in ValidatorEnable(eval(id), false) with document.getElementById(id). It worked for me.
I want to know Id update panel that initial a request in JavaScript .I write this script but it return undefined.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
alert(sender.ID);
}
function EndRequest(sender, args) {
}
sender is not null and it return [object] but How I can get ID?
Edit 1)
I think when UpdatePanel be inside MasterPage it does not work.this is my code:
<script type="text/javascript">
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
var UpdPanelsIds = args.get_updatePanelsToUpdate();
alert(UpdPanelsIds[0]);
}
function EndRequest(sender, args) {
if ($('.AlarmLogo').val() == "3") {
alert('nima');
}
}
});
</script>
and :
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="timer" Interval="4000" runat="server" OnTick="timer_Tick" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlAlarm" runat="server" CssClass="pnlAlarm" ClientIDMode="Static">
<a href="#">
<div id="Alarm">
<asp:TextBox ID="lblContent" runat="server" Text="HHHEEELLLOOO" CssClass="AlarmLogo" ClientIDMode="Static"></asp:TextBox>
</div>
</a>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer" />
</Triggers>
</asp:UpdatePanel>
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</form>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["nima"] = 1;
}
}
protected void timer_Tick(object sender, EventArgs e)
{
}
You can use the get_updatePanelsToUpdate that return an array with the Ids of the UpdatePanels that will be going to updated.
<script>
window.onload = function() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
};
function InitializeRequest(sender, args)
{
// get the array of update panels id
var UpdPanelsIds = args.get_updatePanelsToUpdate();
// get the Post ID
args.get_postBackElement().id;
}
function EndRequest(sender, args) {
}
</script>
http://msdn.microsoft.com/en-us/library/ee224805.aspx
Forgive my English, I had one challenge in my project I,e whenever I started to access hidden field value which in grid view using JavaScript or Jquery, I'm getting compilation error like hidden field doesn't exist in current context so how can I access hidden field value?
SelectPatientInfo.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="Server">
<script type="text/javascript">
function DispValue(sender, e) {
var id = e.get_value();
document.getElementById("<%=PatientRefferalId.ClientID%>").value=id; //getting error here
}
</script>
<div align="left" style="float: left; margin-left: 5px;">
<asp:GridView ID="gvPatient" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="12px" HeaderStyle-Height="20px">
<HeaderTemplate> Patient Name </HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="PatientRefferalId" runat="server" Value="0" />
<PUC:PatientUserControl ID="pucPatient1" runat="server" OnClientSelect="DispValue" PTStatusShow="0"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>
SelectPatientInfo.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
try {
if (!IsPostBack) {
dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt = AddRow(dt);
gvPatient.DataSource = dt;
gvPatient.DataBind();
}
} catch (Exception ex) {
}
}
private DataTable AddRow(DataTable dt) {
for (int i = 0; i < 5; i++) {
DataRow dr = dt.NewRow();
dr[0] = "";
dr[1] = ""; dt.Rows.Add(dr);
}
return dt;
}
protected void GridPatient_DataBound(object sender, EventArgs e) {
try {
foreach (GridViewRow item in gvPatient.Rows) {
HiddenField hfReferralId = (HiddenField)item.FindControl("PatientRefferalId");
Response.write(hfReferralId.Value);
}
} catch (Exception ex) {
}
}
I'm not sure the code
document.getElementById("<%=PatientRefferalId.ClientID%>")
will work, because you don't have only one "PatientRefferalId", but you get many (as many as numbers of rows in your gridview).
I don't know if there is a cleaner way, but I can do what you want by using this javascript code
var gv = document.getElementById("<%=gvPatient.ClientID%>");
var Rows = gv.getElementsByTagName("tr"); // Get all the rows from your gridview (rendered as html table).
// you can loop through the rows or if you know the row index, you can do:
alert(Rows[2].childNodes[0].children[0].value); // Show you the first control (the hiddenfield) of the first cell of the row #2.
Hi This post may help you.
var c = document.getElementsByTagName("table");
for (var i = 0; i < c.length; i++) {
if (c[i].id.indexOf("GridView1") > -1) {
var hidd = c[i].getElementsByTagName("input");
for (var j = 0; j < hidd.length; j++) {
if (hidd[j].type == "hidden")
alert(hidd[j].id);
}
}
}
And also refer following link .. its working to me..
http://forums.asp.net/p/1510265/3603566.aspx/1?Re+how+to+find+gridview+hidden+label+value+from+javascript
<asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="Server">
<script type="text/javascript">
function DispValue(btnShow) {
var parentRow = $(btnShow).closest("tr");
var hiddenField=parentRow.find('input[id$=PatientRefferalId]');
alert(hiddenField.val());
return false;
}
</script>
<div align="left" style="float: left; margin-left: 5px;">
<asp:GridView ID="gvPatient" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="12px" HeaderStyle-Height="20px">
<HeaderTemplate> Patient Name </HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="PatientRefferalId" runat="server" Value="0" />
<asp:LinkButton ID="lnkPopUp" runat="server" Style="font-size: 16px;" OnClientClick="return DispValue(this)" Text="PopUp"
></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>