jQuery in .net validate dropdownlist, fadein and fadeout panels - c#

I have a dropdownlist control ddlAffilation, a panel pnlForms, a panel Complete, a button Submit, a button Return.
I have a validationcontrol on the dropdownlist.
here is my jquery code
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function () {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
});
</script>
I have 2 problems:
1) With this jQuery code, I can go back and forth (fade out pnlForms, fade in Complete when click on Submit and vice versa when click on Return) only when i don't choose any value in the dropdownlist box. If I choose any value in the dropdownlist, the Return button doesn't work.
2) The jquery code bypass the .net server validation control. I need the code not do anything if no value is selected from the dropdownlist. I have tried
var isValid = true;
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
isValid = false;
return false;
}
if (isValid == true) {
...
but it doesn't work. What's the best way to do this?
Thanks,
==================================================================================
I can't add an answer to my own question so I reply to John here:
Thanks John. I have my code like this and it solves problem 2.
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
alert('blah2');
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
However, problem 1 still exists. Let me clarify. I have a few textboxes, a dropdownlist and a submit button to collect feedback from the users. They are all in the panel pnlForms.
All controls can be empty except for the dropdownlist. We took care of this using your code and a server validation control.
when the users click the submit button, I want the pnlForms to fadeOut and a hidden panel called pnlComplete to fadeIn. The pnlComplete has a text saying thanks for the feedback and a button called Return that let the users send another feedback.
When the users click on the Return button, the opposite happens here. The pnlComplete fadeOut and the pnlForms fadeIn.
The Submit button works well but the Return button doesn't work at all. I set some alert() inside the Return.click(function but it doesn't hit.
Any ideas?
Here is the code of the whole page.
<%# Page Title="" Language="C#" MasterPageFile="~/Master.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="Server">
<asp:UpdatePanel ID="pnlForms" runat="server">
<ContentTemplate>
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<asp:TextBox ID="Name" runat="server" Width="150px"></asp:TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<asp:DropDownList ID="ddlAffilation" runat="server" Width="155px">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
<asp:ListItem>F</asp:ListItem>
<asp:ListItem>S</asp:ListItem>
<asp:ListItem>T</asp:ListItem>
</asp:DropDownList>
<em class="required">Required
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage=" - Please select your affiliation"
ControlToValidate="ddlAffilation" SetFocusOnError="True" ForeColor=""></asp:RequiredFieldValidator>
</em></li>
</ol>
</fieldset>
<div style="text-align: center;">
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="submit_Click" /></div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="Complete" style="display: none;">
<asp:UpdatePanel ID="pnlComplete" runat="server">
<ContentTemplate>
<p>Thank you</p>
<div style="text-align: center;">
<asp:Button ID="Return" runat="server" Text="Return" /></div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
<asp:Content ID="Content3" runat="server" ContentPlaceHolderID="cpClientScript">
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
</asp:Content>

I'm not sure if I read your question right or not, but if your issue is that you don't want the jquery to continue firing and allow the form to submit if the dropdown is empty do this:
Instead of attaching a .click event to your button, attach a .submit event to your form. Then you want to use e.PreventDefault() to stop the main submit execution if its not valid
Eg:
$("#FORMNAME").submit(function(e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
// Submitting form...
}
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
Also, you should ALWAYS do server validation along with your client validation.. otherwise all someone has to do is directly submit / bypass your javascript checks
Edit for your edit:
Is the return button being created dynamically or is it there on page load? If its dynamic, its probably never getting assigned to in your jquery, as it doesn't exist when it runs.
Here is a quick test you could try:
var returnButton = $("#<%= Return.ClientID %>");
alert(returnButton.attr("id");
If you don't get back the ID of your return button, its not matching up in your code and thats why your click event isn't working. If thats the case, do a view source on your page and find out what the actual return button ID is set to (this is easier with FireBug or similar tool)

Adding this as a separate answer since its just a huge chunk of code that isn't exactly related to the original answer, but does work as intended. I took the code you gave and converted to basic html from asp.net, and it does work correct, does it work for you?
Could you try posting the output from the asp.net page instead of the code itself? Maybe something isn't being set right on the button element's ID.
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js" type="text/javascript"></script>
</head>
<body>
<div ID="Content1">
<div ID="pnlForms">
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<textbox ID="Name" runat="server" Width="150px"></TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<select ID="ddlAffilation" Width="155px">
<option Value="" Selected="True">--Select One--</option>
<option>F</option>
<option>S</option>
<option>T</option>
</select
</li>
</ol>
</fieldset>
<div style="text-align: center;">
<Button ID="Submit" Value="Submit" OnClick="submit_Click">Submit</Button></div>
</div>
<div id="Complete" style="display: none;">
<div ID="pnlComplete">
<p>Thank you</p>
<div style="text-align: center;">
<Button ID="Return" Value="Return">Return</Button></div>
</div>
</div>
</div>
<div ID="Content3">
<script type="text/javascript">
$(document).ready(function () {
$("#Submit").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#pnlForms").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#Return").click(function () {
$("#Complete").fadeOut('slow');
$("#pnlForms").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#ddlAffilation").val() == "") {
return false;
}
return true;
}
});
</script>
</div>
</body>
</html>

Related

Why do `JQuery` tabs lose styling after a button click

I am using JQuery tabs in my Asp.Net/C# app.
I am modelling my approach after this article. The JQuery is outside of my
<asp:UpdatePanel ID="UpdatePanel1"...></asp:UpdatePanel>
wrapper while the html components are inside.
Whenever I click a button, my tabs completely lose their CSS styling and I see all of the tab contents, rather than just the
<div id="current-tab">
for that tab.
Why is this happening and how do I fix it?
My guess is that its related to post-back or the update panel somehow, but I am not sure why the added C# code under page_load doesn't keep the selected tab current on post-back when the button is fired.
ASPX
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
...
</script>
....
<table>
<tr>
<td style="padding: 5px;">
<div id="tabs">
<ul>
<li>Tier 1</li>
<li>Tier 2</li>
<li>Tier 3</li>
<li>Tier 4</li>
</ul>
<div class="tab-content">
<div id="tab-1">
...
</div>
<div id="tab-2">
...
</div>
<div id="tab-3">
...
</div>
<div id="tab-4">
...
</div>
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
...
selected_tab.Value = Request.Form[selected_tab.UniqueID];
...
}
You are right, it has something to do with a Partial PostBack. So in order for jquery functions to work again you need to rebind it after the Partial PostBack is done.
<script type="text/javascript">
$(document).ready(function () {
buildTabs();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
buildTabs();
});
function buildTabs() {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
}
</script>
But the selected tab is a different story. You also need to store the active tab somewhere and re-apply it after the partial PostBack is done. See this answer for details.
But basically you need to store the active tab ID in SessionStorage, cookie or Hiddden input and re-apply it in prm.add_endRequest(function () {

How to position cursor from textbox1 to textbox2 in ASP.Net?

I have two textboxes in my web application for login page, RegNo and Address. Now I want that if the page loads then cursor should be on RegNo textbox . After entering RegNo it must goes to Address after press Enter. How to do This?
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body bgcolor="#CCCCCC" >
<form id="form1" runat="server">
<div>
<asp:TextBox ID="RegNo" runat="server" Text=""></asp:TextBox>
<asp:TextBox ID="Name" runat="server" Text=""></asp:TextBox>
<asp:TextBox ID="Address" runat="server" Text=""></asp:TextBox>
<asp:Button CssClass="sCancel" ID="btnCancel" runat="server" Text="Close" onclick="btnCancel_Click" Width="84px" />
<asp:Button CssClass="sUpdate" ID="btnUpdate" runat="server" Text="Update" onclick="btnUpdate_Click" Width="84px" style="margin-left: 0px"/>
<asp:Button CssClass="sAdd" ID="Add" runat="server" Text="Add" Width="84px" onclick="Add_Click" />
</div>
</form>
</body>
</html>
Well, I assume what you ask is how to change focus from userid to password and you don't need to move cursor itself.
Note that there is no need to do this in server side. You are able to simply do this in client side with JQuery. If you are not familiar with JQuery see here to understand how to add JQuery to your client side code.
Now I assume code in your client side is something like this:
Username: <asp:TextBox name="userid" id="userid" /><br>
Password: <asp:TextBox name="password" id="password" />
I will provide two examples with JQuery for this, in first example the focus will jump to password when user press Enter:
$('#userid').keydown(function (e) {
if (e.keyCode == 13) {
$("#password").focus();
return false;
}
});
In next example we change focus to password when userid reaches a specific lengths. for example 6:
$('#userid').keydown(function (e) {
if ($("#userid").val().length > 5) {
$("#password").focus();
}
});
UPDATE
It should work in your code:
<head runat="server">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('#RegNo').keydown(function (e) {
if (e.keyCode == 13) {
$("#Name").focus();
return false;
}
});
});
</script>
</head>
<body bgcolor="#CCCCCC">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="RegNo" runat="server" Text=""></asp:TextBox>
<asp:TextBox ID="Name" runat="server" Text=""></asp:TextBox>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#RegNo').keydown(function (e) {
if (e.keyCode == 13) {
$("#Name").focus();
return false;
}
});
$('#Name').keydown(function (e) {
if (e.keyCode == 13) {
$("#Address").focus();
return false;
}
});
$('#Address').keydown(function (e) {
if (e.keyCode == 13) {
$("#Add").focus();
return false;
}
});
});
</script>
You can achieve this by the use of Tabindex Property of TaxtBox.
First, You set the Tabindex=1 to Textbox1
then,set the Tabindex =2 to TextBox2 and so on..
By this when your page is load then it look tabindex of control which is less it focus on that.
Thanks

Unable to change visibility of a div in asp.net C#

I have a div that displays loading symbol. I am setting visibility on change of a dropdown box. I want to set its visibility to false in C# after the SelectedIndexChanged method is complete.
Here is the div tag :
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage" >
<img class="loadingImg" src="../Images/ajax-loader.gif" />
</div>
Here is the jQuery function :
$(document).ready(function () {
//$('#loadingImage').hide();
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "block";
});
});
and this is how i am trying to set the visibility in C#
protected void selectSegment_SelectedIndexChanged(object sender, EventArgs e)
{
ckBLBusinessUnits.Visible = true;
loadingImage.Style["display"] = "none";
}
I tried various ways in C# like set visibility to false etc but nothing worked. Kindly help.
Change this:
loadingImage.Style["display"] = "none";
To this:
loadingImage.Style.Add("display", "none");
You can use hide and show methods to perform that action.
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage">
<img class="loadingImg" src="loading.gif" />
</div>
<asp:DropDownList ID="selectSegment" ClientIDMode="Static"
runat="server">
<asp:ListItem Value="0">none</asp:ListItem>
<asp:ListItem Value="1">display</asp:ListItem>
</asp:DropDownList>
JS
$(document).ready(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
if (this.value === "1") {
$("#loadingImage").show();
} else {
$("#loadingImage").hide();
}
});
});
The div tag was outside of the updatepanel, moving the div inside of the updatepanel resolved the issue.

Asp.NET OnMouseOver and OnMouseOut clientside

I hope someone can give me a hint about what should I do in this case. I want to show a notification email. I have a timer that fires passing a time. If someone mouseover the linkbutton then will show all the emails and if out then dissapears. The fact is when I am trying to select one of the emails the content (which has the emails) dessapears because of the mouseout. What should I do to avoid this? Thanks in advance!!! by the way I get my emails at onmouseover and close on out.
<asp:Timer ID="TimerNew" runat="server" Interval="10000" OnTick="TimerNew_Tick" Enabled="false"></asp:Timer>
<asp:Panel ID="PanelTools" runat="server" >
<div runat="server" id="DropDownMenu">
<asp:LinkButton ID="LinkButton" runat="server" onmouseover="OnClientMouseOver()" onmouseout="OnClientMouseOut()">
</asp:LinkButton>
<div id="divEmails" runat="server">
<div class="dropdown-content">
<ul id="emailList" runat="server">
</ul>
</div>
</div>
</div>
</asp:Panel>
Here is my javascript function.
function OnClientMouseOver(obj, event)
{
var isOpen = '<%= this.Open %>';
if (isOpen == false)
{
__doPostBack('OpenEmails');
}
}
function OnClientMouseOut(obj, event)
{
var isOpen = '<%= this.Open %>';
var e = event.toElement || event.relatedTarget;
if (e.parentNode == this || e == this)
{
return;
}
__doPostBack('CloseEmails');
}
this.Open is a variable (viewstate to dont lose it). I use telerik RadAjaxProxyManager, I do an ajax postback and execute my server methods.

jQuery UI Dialog shown using an ASP.NET button

I'm trying to show a modal dialog when the user click on an ASP.Net button. This is my page:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.6.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 300,
modal: true,
buttons: {
'Ok': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
;
}
});
});
function ShowDialog() {
$('#dialog').dialog('open');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="TreeNew" runat="server" Text="New" OnClientClick="ShowDialog();"/>
<asp:Label ID="Message" runat="server"></asp:Label>
<div id="dialog" title="Select content type">
<p id="validateTips">All form fields are required.</p>
<asp:RadioButtonList ID="ContentTypeList" runat="server">
<asp:ListItem Value="1">Text</asp:ListItem>
<asp:ListItem Value="2">Image</asp:ListItem>
<asp:ListItem Value="3">Audio</asp:ListItem>
<asp:ListItem Value="4">Video</asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
</form>
</body>
</html>
When I click on TreeNew button appears modal popup but inmediately the page do postback.
What's happening?
While adding a return false; will fix your problem (as suggested by other answers), I think the best thing for you to do is use a standard HTML button. There is no reason to use an ASP.NET control in this case since you do not intend to postback.
If you insist to use a ASP.NET button, however, at least set UseSubmitBehavior="False" so that the button is rendered as <input type="button"/> instead of <input type="submit"/>.
Try
OnClientClick="return ShowDialog();"
AND
function ShowDialog() {
$('#dialog').dialog('open');
return false;
}
This will prevent the postback.
Your OnClientClick needs to return false like so:
OnClientClick="ShowDialog(); return false;"
Buttons by default postback but return false prevents the default behavior
You're not returning false from your OnClientClick. When you don't explicitly return false, "true" in this situation is assumed. A return value of true from your OnClientClick indicates it's fine to do a postback. Try changing OnClientClick to the following (adding "return false" after your call to ShowDialog())
OnClientClick="ShowDialog();return false;"
This article maybe of some value to you: using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control.
Hope this helps some.
Use preventDefault() jQuery function to prevent button postback
Try this:
function ShowDialog(evt) {
evt.preventDefault();
$('#dialog').dialog('open');
}

Categories

Resources