If checkbox checked and textbox blank - c#

I have a checkbox, on click of which the textbox gets enabled. I want to make validation that If checkbox is checked and the user doesn't put any data. It should not allow the user to submit the form. Please see the javascript code for your reference
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$('#chkCropLoan').change(function () {
$("#txtAmount").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtAmount").val("");
}
});
$('#chkInvestmentLoan').change(function () {
$("#txtInvestmentLoan").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtInvestmentLoan").val("");
}
});
$('#chkWarehouseReceipt').change(function () {
$("#txtWarehouseReceipt").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtWarehouseReceipt").val("");
}
});
$('#chkFarmerProd').change(function () {
$("#txtFarmerProd").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtFarmerProd").val("");
}
});
});
</script>
HTML code of textbox :
<table>
<tr>
<td>Crop Loan</td>
<td>
<asp:CheckBox ID="chkCropLoan" runat="server" CssClass="check" onclick="javascript:enableTextBox();" />
<asp:TextBox ID="txtAmount" runat="server" class="txtfld-popup1" MaxLength="5" Width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtAmount_TextBoxWatermarkExtender" runat="server" TargetControlID="txtAmount" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
<asp:RegularExpressionValidator ID="rgfldvalidator" ControlToValidate="txtAmount"
runat="server" ErrorMessage="Please enter the numbers only" ValidationExpression="^[0-9]*\.?[0-9]+$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Investment Loan</td>
<td>
<asp:CheckBox ID="chkInvestmentLoan" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtInvestmentLoan" runat="server" class="txtfld-popup1" MaxLength="5" width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtInvestmentLoan_TextBoxWatermarkExtender" runat="server" TargetControlID="txtInvestmentLoan" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" ControlToValidate="txtInvestmentLoan"
runat="server" ErrorMessage="Please enter the numbers only" ValidationExpression="^[0-9]*\.?[0-9]+$"></asp:RegularExpressionValidator>
</td>
</tr>
</tr>
<tr>
<td>Warehouse Receipt Finance</td>
<td>
<asp:CheckBox ID="chkWarehouseReceipt" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtWarehouseReceipt" runat="server" class="txtfld-popup1" MaxLength="5" Width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtWarehouseReceipt_TextBoxWatermarkExtender" runat="server" TargetControlID="txtWarehouseReceipt" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
</td>
</tr>
<tr>
<td>Farmer Producer Companies</td>
<td>
<asp:CheckBox ID="chkFarmerProd" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtFarmerProd" runat="server" class="txtfld-popup1" MaxLength="5" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Width="100" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender11" runat="server" TargetControlID="txtFarmerProd" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
</td>
</tr>
</table>

Try:
$("#your-form").submit(function() {
if($(this).find("#your-text").val() && $(this).find("#your-check").checked){
$("#your-form").submit();
}
else{
// not checked or empty textbox
}
return false;
});

Try using the below code:
$('#your_form_name').submit(function( event ) {
if ($('#chkCropLoan').is(':checked') && $('#txtAmount').val() == '') {
alert('error message');
event.preventDefault();
}
});

you don't want to submit form if Text box is Empty
just write function on submit button click event
<input type="submit" value="save" onclick="return checkvalid()" />
In script
<script type="text/javascript">
function checkvalid() {
if (document.getElementById('textboxId').value==""
|| document.getElementById('textboxId').value==undefined) {
return false;
}
</script>

Related

SweetAlert confirmation dialog with asp.net listview delete?

Please help me fathom this.
I have created a ListView, displaying data from a SQL database. I have enabled inserting, editing and deleting and it all works.
What do I want?
I want to use SweetAlert to prompt the user to confirm yes/no whether they want to delete the entry from the ListView or not.
What have I done?
First I tried using the "builtin" functionality where I added OnClientClick="return confirm('are you sure')" to the <asp:Button/> calling the delete of the given ListView entry. That worked! When I clicked yes it deleted and no it didn't. I didn't have to do anything other than add the above. But It is not what I want. I want the fancier SweetAlert to be displayed, and here the problem starts.
Second I thought I could simply create the SweetAlert script and call its function name from the button. However when doing so, it does open SweetAlert but before I even get the chance to click yes and no, it has already deleted the item and closes the box.
<script>
function deletealert()
{
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
</script>
Now I know that there is no functionality in the above, but I didn't even get the chance to move to the yes and no, it closed the script by itself. Then I found out that I could stop the deleting by setting CausesValidation=false on the delete <asp:Button /> but then nothing happened at all.
Third I think I have a breakthrough, but I have no clue how to finish it. I found out that on the ListView, there is an event called ItemDeleting. This event fires before the delete is executed. I tested it out, and it works.
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true); //Calls the sweetalert
e.Cancel = true;
//e.Cancel = false;
}
If I use the e.Cancel = true; then the item is not deleted and the action is cancelled. If I use the e.Cancel = false; then the item is deleted. So I think I may have to incorporate that functionality with the above jQuery. I don't know if I can put jQuery inside the protected void and work with it from there either?
Updated to include suggested solution from haraman Here is also the entire .aspx page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="forum-front.aspx.cs" Inherits="initial.site.forum_front" EnableViewState="true" EnableEventValidation="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="Content/sweetalert.min.js"></script>
<%--CSS Style Sheets--%>
<link href="Content/Styles.css" rel="stylesheet" />
<link href="Content/StylesPanel.css" rel="stylesheet" />
<link href="Content/sweetalert.css" rel="stylesheet" />
<%--Java Scripts--%>
<script>
function deletealert(ctl) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
// RESUME THE DEFAULT LINK ACTION
eval(defaultAction);
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
</script>
<asp:Panel ID="Panel1" runat="server" Height="1401px">
<center>
<table>
<tr>
<td>
<asp:Button ID="TilForsiden" runat="server" OnClick="TilForsiden_Click" Text="Forsiden" CssClass="button" />
</td>
<td>
<asp:Panel ID="Panel2" runat="server" CssClass="panel panel-default">
<h1><asp:Label ID="ForumOverskrift" runat="server" CssClass=""></asp:Label></h1>
</asp:Panel>
</td>
</tr>
</table>
</center>
<center>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" InsertItemPosition="LastItem" DataKeyNames="OpslagsID" OnDataBound="SkrivOpslag_Click">
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton1" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Rediger" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</AlternatingItemTemplate>
<EditItemTemplate>
<tr style="">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="btn-default" />
</td>
<td>
<asp:TextBox ID="IndholdTextBox" runat="server" Text='<%# Bind("Indhold") %>' />
</td>
<td>
<asp:TextBox ID="EmneTextBox" runat="server" Text='<%# Bind("Emne") %>' />
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<InsertItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="EmneTextBox" Placeholder="Emne..." runat="server" Text='<%# Bind("Emne") %>' CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="IndholdTextBox" Placeholder="Skriv her..." runat="server" Text='<%# Bind("Indhold") %>' CssClass="form-control" ToolTip="Skriv dit indhold her" TextMode="MultiLine" Rows="8" Width="500px" />
</td>
</tr>
</table>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Udgiv" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Ryd" CssClass="btn-default" />
</td>
<td></td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton2" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="" class="table table-striped">
<tr runat="server" style="">
<th runat="server"></th>
<th runat="server">Indhold</th>
<th runat="server">BrugerNavn</th>
<th runat="server">Postnummer</th>
<th runat="server">Emne</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Button ID="SkrivOpslag" runat="server" CommandName="SkrivOpslag" Text="Skriv Opslag" CssClass="btn btn-default btn-xs" OnClick="SkrivOpslag_Click" />
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" FirstPageText="Første Side" ShowLastPageButton="True" LastPageText="Sidste Side" PreviousPageText="Forrige" NextPageText="Næste" ButtonCssClass="btn btn-default" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" CssClass="btn btn-default btn-xs" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
</center>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="True" ConnectionString="<%$ ConnectionStrings:foradbConnectionString %>" DeleteCommand="DELETE FROM [testOpslagstabel] WHERE [OpslagsID] = #OpslagsID" InsertCommand="INSERT INTO [testOpslagstabel] ([Indhold], [DatoTid], [Reference], [BrugerNavn], [Emne], [Postnummer]) VALUES (#Indhold, GetDate(), #Reference, 'testuser', #Emne, #Postnummer)"
SelectCommand="SELECT * FROM [testOpslagstabel] WHERE ([Postnummer] = #Postnummer)" UpdateCommand="UPDATE [testOpslagstabel] SET [Indhold] = #Indhold, [DatoTid] = #DatoTid, [Reference] = #Reference, [BrugerNavn] = 'testuser', [Postnummer] = #Postnummer, [Emne] = #Emne WHERE [OpslagsID] = #OpslagsID"
InsertCommandType="Text">
<DeleteParameters>
<asp:Parameter Name="OpslagsID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
<asp:Parameter Name="OpslagsID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Panel>
</asp:Content>
Just to make everything more clear I'm updating the post with the full code in my code behind the aspx. Also if it makes the understanding better, I'm trying to create a forum.
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace initial.site
{
public partial class forum_front : System.Web.UI.Page
{
string qbynavn;
object objbynavn;
// Makes the SQL connection string
String CS = ConfigurationManager.ConnectionStrings["FORADB"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string qpostnr = Request.QueryString["Postnummer"];
if (qpostnr != null)
{
try
{
using (SqlConnection con = new SqlConnection(CS))
{
// specifies the command to check for zipcode
SqlCommand cmd = new SqlCommand("SELECT Bynavn FROM Postnummertabel WHERE Postnr = " + qpostnr, con);
// Opens the connection
con.Open();
objbynavn = cmd.ExecuteScalar();
qbynavn = objbynavn.ToString();
ForumOverskrift.Text = " Velkommen til " + qbynavn;
}
}
catch (Exception ex)
{
Response.Write("Der opstod en fejl! " + ex.Message);
}
}
else
{
ForumOverskrift.Text = " Velkommen!";
}
}
public void AnswerButton_Click(object sender, EventArgs e)
{
// Tries to bind the sender to the right button.
Button originator = sender as Button;
// Checks if it has been found
if (originator != null)
{
// Goes throug the control hierachy to find the right item.
var parentItem = originator.Parent as ListViewItem;
if (parentItem != null
&& parentItem.ItemType == ListViewItemType.DataItem)
{
// Binds the textbox and button to variables
var textBox = parentItem.FindControl("AnswerTextBox") as TextBox;
var btn = parentItem.FindControl("AnswerButton") as Button;
if (textBox != null)
{
// Changes the textbox to being visible and changes the buttons text.
if (textBox.Visible == false)
{
textBox.Visible = true;
btn.Text = "Fortryd";
}
// Changes the textbox to invisible and changes the buttons text.
else if (textBox.Visible == true)
{
textBox.Visible = false;
btn.Text = "Svar";
}
}
}
}
}
// Makes the Skriv Opslag field either visible or invisible
protected void SkrivOpslag_Click(object sender, EventArgs e)
{
if (ListView1.InsertItem.Visible == true)
{
// Makes the Skriv Opslag field invisible
ListView1.InsertItem.Visible = false;
// Changes the buttons name to Skriv Opslag
Button btn = (Button) ListView1.FindControl("SkrivOpslag");
btn.Text = "Skriv Opslag";
}
else if (ListView1.InsertItem.Visible == false)
{
// Makes the Skriv Opslag field visible
ListView1.InsertItem.Visible = true;
// Changes the Buttons name to Skriv Opslag
Button btn = (Button)ListView1.FindControl("SkrivOpslag");
btn.Text = "Fortryd";
}
}
protected void TilForsiden_Click(object serder, EventArgs e)
{
Response.Redirect("~/welcomepage.aspx");
}
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true);
//e.Cancel = true;
//Response.Write("<script>deletealert();</script>");
//ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "deletealert();", true);
}
}
}
First you must understand that you can not mix server side code then client side code and then again server code in one go as you are currently doing in ItemDeleting event. All client side code will fire only when the page PostBacks after completing the server side code execution.
Now, with regard to your use of plugin. Have you returned anything from the swal function?
Lets try to do it the old way using your first method OnClientClick="return confirm('are you sure')". Modify it to OnClientClick="return deletealert();". Now in JavaScript return true/false in your deletealert function (focus on comments in CAPITALS)
... YOUR OTHER CODE IN DELETEALERT
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
//RETURN TRUE TO EXECUTE SERVER CODE
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
//RETURN FALSE TO SKIP SERVER CODE
return false;
}
});
... YOUR OTHER CODE
Update:
The working of SweetAlert is somewhat different from a regular alert. It does shows a modal window but does not prevent any action initiated by the user such as submit, link click. So the workaround is to store the href of the link in a var, show SweetAlert and then use eval to resume that link.
function deletealert(ctl, event) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({ title: "Deleted!", text: "Your imaginary file has been deleted.", type: "success", confirmButtonText: "OK!", closeOnConfirm: false },
function () {
// RESUME THE DEFAULT LINK ACTION
window.location.href = defaultAction;
return true;
});
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
I have replaced the asp:Button with asp:LinkButton just for easy handling of preventDefault and then resuming the operation.
<asp:LinkButton OnClientClick="return deletealert(this, event);" ID="DeleteButton" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
Only one small glitch needs to be tackled is when the user finally clicks the ConfirmButton the final success message is displayed but at the same time the default action is also executed resulting in a postback. Updated to postback after final success message and FireFox update.
You need to prompt before you get to the server; so attach to the delete button click using jQuery:
$("#idofplaceholderwrappingtheitems").find("[id$='DeleteButton']").on("click", function(e) {
//show confirmation here;
});
Showing the javascript in ItemDeleting is too late in the process.

why is my page passing a blank value for my textBox

I asked this question last night but it was not very well written so I am going to ask it again. I am creating a simple calculator using ASP.NET and c# as my code behind. I am currently just trying to test and make sure that my code behind is getting the value typed entered into the textbox by the user. I put in a if statement that assigns the textbox a value of mehhh if the string it gets passed it empty. My text box displays mehhh so I knoe it is getting an empty string but i am not sure why? here is a link to the site... http://scort323.csweb.kutztown.edu/Calc.aspx Below is my code for the code behind part of my page:
public partial class Assign2_Calc : System.Web.UI.Page
{
protected void ButtonEqual_Click(object sender, EventArgs e)
{
string inputStr = inputBox.Text;
if (inputStr == string.Empty)
{
inputBox.Text = "mehhhhhh";
}
else
{
inputBox.Text = inputStr; //result.ToString();
}
}
}
below is my .aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Calc.aspx.cs"
Inherits="Assign2_Calc" Debug="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="CalculatorStyle.css" rel="stylesheet" type="text/css" />
<script>
var maxInputLength = 20;
function checkButtonClick(clickedValue) {
var buttonValue = clickedValue;
var inputStr = document.getElementById('inputBox').value;
if (buttonValue == '<--') {
if (inputStr.length >= 1) {
document.getElementById('inputBox').value = inputStr.substring(0, inputStr.length - 1);
}
}
else if (buttonValue == 'C') {
document.getElementById('inputBox').value = "";
}
else {
if (inputStr.length < maxInputLength) {
document.getElementById('inputBox').value = inputStr + buttonValue;
}
else {
//document.getElementById('msg').innerHTML = "Maxmum length is " + maxInputLength;
}
}
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="main" class="main">
<div id="content" class="content">
<h3 id="h3">Simple Calculator</h3>
<div id="calculatorDiv">
<table cellpadding="0" cellspacing="0">
<tr>
<td colspan="4">
<asp:TextBox runat="server" CssClass="inputBox" ReadOnly="true" ViewStateMode="Enabled" ID="inputBox"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="4">
<br />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonNum7" runat="server" Text="7" CssClass="CalcButtons" OnClientClick="return checkButtonClick(7)" />
</td>
<td>
<asp:Button ID="ButtonNum8" runat="server" Text="8" CssClass="CalcButtons" OnClientClick="return checkButtonClick(8)" />
</td>
<td>
<asp:Button ID="ButtonNum9" runat="server" Text="9" CssClass="CalcButtons" OnClientClick="return checkButtonClick(9)" />
</td>
<td>
<asp:Button ID="ButtonDivide" runat="server" Text="/" CssClass="CalcButtons" OnClientClick="return checkButtonClick('/')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonNum4" runat="server" Text="4" CssClass="CalcButtons" OnClientClick="return checkButtonClick(4)" />
</td>
<td>
<asp:Button ID="ButtonNum5" runat="server" Text="5" CssClass="CalcButtons" OnClientClick="return checkButtonClick(5)" />
</td>
<td>
<asp:Button ID="ButtonNum6" runat="server" Text="6" CssClass="CalcButtons" OnClientClick="return checkButtonClick(6)" />
</td>
<td>
<asp:Button ID="ButtonMultiply" runat="server" Text="*" CssClass="CalcButtons" OnClientClick="return checkButtonClick('*')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="1" CssClass="CalcButtons" OnClientClick="return checkButtonClick(1)" />
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="2" CssClass="CalcButtons" OnClientClick="return checkButtonClick(2)" />
</td>
<td>
<asp:Button ID="Button3" runat="server" Text="3" CssClass="CalcButtons" OnClientClick="return checkButtonClick(3)" />
</td>
<td>
<asp:Button ID="ButtonSubtract" runat="server" Text="-" CssClass="CalcButtons" OnClientClick="return checkButtonClick('-')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonDackspace" runat="server" Text="<--" CssClass="CalcButtons" OnClientClick="return checkButtonClick('<--')" />
</td>
<td>
<asp:Button ID="ButtonNum0" runat="server" Text="0" CssClass="CalcButtons" OnClientClick="return checkButtonClick(0)" />
</td>
<td>
<asp:Button ID="ButtonClear" runat="server" Text="C" CssClass="CalcButtons" OnClientClick="return checkButtonClick('C')" />
</td>
<td>
<asp:Button ID="ButtonAdd" runat="server" Text="+" CssClass="CalcButtons" OnClientClick="return checkButtonClick('+')" />
</td>
</tr>
<tr>
<td colspan="4">
<asp:Button ID="ButtonEqual" runat="server" Text="=" CssClass="CalcButtonEqual" OnClick="ButtonEqual_Click" />
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Looking at the source of your web page I found that you have disabled your textbox. If a control is disabled it cannot be edited and its content is excluded when the form is submitted. So instead of disabling (remove disable attribute completely) your textbox set it to readonly (readonly = 'true').
MSDN doc on ReadOnly:
The Text value of a TextBox control with the ReadOnly property set to true is sent to the server when a postback occurs, but the server does no processing for a read-only text box. This prevents a malicious user from changing a Text value that is read-only. The value of the Text property is preserved in the view state between postbacks unless modified by server-side code.
You are "manipulating" the value in client script (not in server code - assuming above is all the code). The original value of the TextBox is preserved (empty).
If you test by removing the ReadOnly attribute (or set it to False), your code will work and you will see the effect of the setting...
Hth....
Update:
..how would I need to go about making it so the user cant use the keyboard to enter anything? making it so they must use the buttons
Unless you have/had a reason to use a server-side control for that input field, a standard HTML Input field with readonly should work.
You will then obtain it's value from the standard POST in the Request (at the end of the day, WebForms is still an HTTP POST), instead of ASP.Net controls.
Trivial example:
Instead of server-control:
<asp:TextBox runat="server" CssClass="inputBox" ReadOnly="true" ViewStateMode="Enabled" ID="inputBox"></asp:TextBox>
Use plain html input field:
<input id="inputBox" name="inputBox" readonly type="text" />
The value of the field (html_readonly) can be obtained in the POST Request:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string _html = Request["inputBox"]; //here it is
//do whatever...
}
}
Hth...

Find Controls nested inside Repeater Control

I'm trying to find the values of TextBoxes which are rendered in a Repeater though a UserControl, i.e. the Repeater has a Placeholder for the UserControl, and inside the UserControl is where the TextBox markup actually exists. I've done this before with TextBoxes directly inside of a Repeater before, which was fairly straight forward, and I'm wondering why this apparently can't be accomplished the same way. Here is the Default page with the Repeater, which contains a Placeholder...
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<form class="formee">
<fieldset>
<legend>Faculty Information</legend>
<div class="grid-4-12">
<asp:Label ID="lblFirstName1" runat="server" Text="First Name"></asp:Label>
<asp:Label ID="lblFirstName2" runat="server" Text="" ></asp:Label>
<asp:Label ID ="lblSalary" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</div>
<div class="grid-6-12">
<asp:Label ID="lblLastName1" runat="server" Text="Last Name"></asp:Label>
<asp:Label ID="lblLastName2" runat="server" Text=""></asp:Label>
</div>
</fieldset>
</form>
<div id="repeaterDiv">
<asp:Repeater ID="rptBudget" runat="server" ClientIDMode="Static">
<ItemTemplate>
<asp:PlaceHolder ID="phBudget" runat="server" EnableViewState="true" />
<br />
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnAddBudgetControl" runat="server" Text="Add"
CausesValidation="false" OnClick="AddBudgetControl" CssClass="addBudgetControl"/>
<asp:Button ID="btnDisplayEntries" runat="server" Text="Display Entries" CausesValidation="false" OnClick="DisplayEntries" />
</div>
<div>
<asp:TextBox ID="txtTotalPercent" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:TextBox ID="txtGrandTotal" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="lblCtrls" runat="server" Text=""></asp:Label>
</div>
...and the UserControl which is inserted in the place of the Placeholder...
<fieldset>
<legend>Faculty Salary Form</legend>
<table cellspacing="10" id="values">
<tr>
<td>
<asp:Label ID="lblServiceType" runat="server" Text="Service"></asp:Label>
<asp:DropDownList runat="server" ID="ddlServiceType" CssClass="serviceType" />
</td>
<td>
<asp:Label ID="lblSpeedCode" runat="server" Text="Speed Code"></asp:Label>
<asp:DropDownList runat="server" ID="ddlSpeedCode" CssClass="speedType" />
</td>
<td>
<asp:Label ID="lblPercentage" runat="server" Text="Percentage"></asp:Label>
<asp:Textbox ID="txtPercentage" runat="server" CssClass="percentCommitment" ClientIDMode="Static" EnableViewState="true" />
</td>
<td>
<asp:Label ID="lblTotal" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="txtTotal" runat="server" CssClass="amountCommitment" ClientIDMode="Static" EnableViewState="true"/>
</td>
<td>
<asp:Button ID="btnRemove" runat="server" Text="Remove Item" OnClick="RemoveItem" ClientIDMode="Static" CssClass="btnRemove" />
</td>
</tr>
<tr>
</tr>
</table>
</fieldset>
...but when the following code runs for the Display button's OnClick, I always get a null value for any and all TextBoxes (and DropDowns) in the UserControl...
protected void DisplayEntries(object sender, EventArgs e)
{
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage = (TextBox)repeated.FindControl("txtPercentage");
if (txtPercentage == null)
{
lblCtrls.Text += " null; ";
}
else
{
lblCtrls.Text += txtPercentage.Text + "; ";
}
}
}
What's the best way to access these values? Thanks.
txtPercentage Textbox is located inside Usercontrol, so use the following helper method to retrieve it.
Helper Method
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Usage
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage =
(TextBox)FindControlRecursive(repeated, "txtPercentage");
...
}
Try loading the placeholder first and then looking for the textboxes in the placeholder:
Something like this:
pseudo
var ph = repeated.FindControl("phBudget");
var txtBox = ph.FindControl("txtPercentage");
/pseudo
You need to first get the UserControl, then use FindControl on the UC itself.

Validating Forms with Jquery

I have a form with 4 dropdownlists whose autopostback property is set to true and each dropdown list gets populated based on the selection of the previous dropdownlist.
Ex. ddlCourseType gets populated after a selection is made in ddlCourseLevel and so on.
I need to validate every textbox and dropdownlist but am having a hard time with the dropdownlists because of its autopostback property.
It will be great if somebody could help me with the best way to validate this form or any tips or advice would be awesome. Thanks a lot. Below is the aspx file that has the jquery function for validating dropdowns and textboxes.
Admin_Course_Edit.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="/JQuery_Plugins/timepicker/js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
<link href="../JQuery_Plugins/timepicker/css/ui-lightness/jquery-ui-1.7.2.custom.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$('#tbStartDate').datepicker({
duration: '',
showTime: true,
constrainInput: false
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="BreadCrumbs" runat="server">
<asp:SiteMapPath ID="SiteMapPath1" runat="server">
</asp:SiteMapPath>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="rightNavigation" runat="server">
<script type="text/javascript">
$(document).ready(function () {
//Function to Validate DatePicker
$.validator.addMethod('isDate', function (value, element) {
var isDate = false;
try {
$.datepicker.parseDate('mm/dd/yy', value);
isDate = true;
}
catch (e) {
}
return isDate;
});
//Function to Validate DropDown Lists
$.validator.addMethod('selectNone',
function (value, element) {
return this.optional(element) ||
(value.indexOf("") == -1); //Leave it blank or enter the exact text in index 0
}, "Please Select an Option");
$("#form1").validate({
// $("#tbStartDate").rules("add", {isDate: true} messages: {isDate: "Date to Validate is invalid."}
rules: {
'<%=ddlCourseLevel.UniqueID %>': { selectNone: true },
'<%=tbStartDate.UniqueID %>': { required: true, isDate: true },
'<%=tbCourseName.UniqueID %>': { required: true, maxlength: 25 },
'<%=tbPointScale.UniqueID %>': { required: true, digits: true },
'<%=tbDescription.UniqueID %>': { maxlength: 50 }
},
messages: { '<%=tbStartDate.UniqueID %>': { isDate: "Please enter a Valid Date"} }
});
$("#imgBtn_A_save").click(function (evt) {
// Validate the form and retain the result.
var isValid = $("#form1").valid();
// If the form didn't validate, prevent the
// form submission.
if (!isValid)
evt.preventDefault();
});
$("#imgBtn_A_cancel").click(function () {
$("#form1").validate().cancelSubmit = true;
});
});
function HideLabel() {
document.getElementById('<%= lblMessage.ClientID %>').style.display = "none";
}
setTimeout("HideLabel();", 2000);
</script>
<div class="Admin_rightNavtop">
<div class="title">
<asp:Label ID="lblTitle" Text="Edit Course" runat="server" class="titleLbl" />
</div>
<p align="center">
<asp:Label ID="lblMessage" runat="server" Style="color: Red" /></p>
<!-- START TABLE ADD FORM-->
<table style="margin-left: 70px">
<tr>
<td>
<asp:Label ID="LblCourseLevel" Text="* Course Level :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:DropDownList ID="ddlCourseLevel" class="ddlSize_large_addEdit" OnSelectedIndexChanged="ddlCourseLevel_SelectedIndexChanged"
AutoPostBack="true" EnableViewState="true" OnDataBound="helperCourseLevel_Databound"
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="CourseType" Text="* Course Type :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:DropDownList ID="ddlCourseType" runat="server" class="ddlSize_large_addEdit"
OnDataBound="helperCourseType_Databound" EnableViewState="true" OnSelectedIndexChanged="ddlCourseType_SelectedIndexChanged"
AutoPostBack="true" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCourseName" Text="* Course Name :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:DropDownList ID="ddlCourseName" class="ddlSize_large_addEdit" OnSelectedIndexChanged="ddlCourseName_SelectedIndexChanged"
AutoPostBack="true" EnableViewState="true" OnDataBound="helperCourse_Databound"
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCourseName2" Text="* New Name :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:TextBox ID="tbCourseName" class="tbSize_large_addEdit" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblStartDate" Text="* Start Date :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:TextBox ID="tbStartDate" runat="server" class="tbSize_large_addEdit" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblGraded" Text="* Grade Type :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:DropDownList ID="ddlGradeType" runat="server" class="ddlSize_large_addEdit"
OnSelectedIndexChanged="ddlGradeType_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>---Select Grade Type---</asp:ListItem>
<asp:ListItem Value="1">Point Scale</asp:ListItem>
<asp:ListItem Value="2">Pass/Fail</asp:ListItem>
<asp:ListItem Value="3">Attendance</asp:ListItem>
<asp:ListItem Value="4">Not Graded</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblPointScale" Text="* Point Scale :" runat="server" class="lblSize_largeGreen"
Visible="false" />
</td>
<td>
<asp:TextBox ID="tbPointScale" runat="server" class="tbSize_large_addEdit" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblDescription" Text="Description :" runat="server" class="lblSize_largeGreen" />
</td>
<td>
<asp:TextBox ID="tbDescription" runat="server" class="tbSize_large_addEdit" />
</td>
</tr>
</table>
<!-- End of Table ADD COURSE-->
</div>
<!-- End of rightNavTop-->
<center>
<div class="Admin_action">
<asp:ImageButton ID="imgBtn_A_save" ImageUrl="../Images/Save.png" OnClick="save_Click"
runat="server" class="Admin_action_imgSize_small" />
<asp:ImageButton ID="imgBtn_A_cancel" ImageUrl="../Images/Cancel.png" runat="server"
class="Admin_action_imgSize_small" CausesValidation="false" OnClick="cancel_Click" />
</div>
</center>
<!-- End selection buttons-->
</asp:Content>
You can add an onchange event to the control and return false if you think it's invalid to cancel the postback.
Personally, I'd want to do the whole shebang using jQuery and AJAX and cut out the nasty auto postback.
The validations for the dependent DDLs will also have to check their "parent" DDL.
DDL 1 - Must be selected
DDL 2 - If DDL 1 is selected must be selected.
DDL 3 - If DDL 2 is selected must be selected.
DDL 4 - If DDL 4 is selected must be selected.
Sorry I don't have time to write up the code, but hopefully this will be helpful.

DefaultButton in Repeater with textbox and button?

I have a repeater, which represents a shoppingbasket. This shopping basket has an "Update quantity" and a "Delete item" button.
When you edit the quantity and click enter, I will need it to use the Update quantity button (unlike now where it uses the delete item button).
In the code I've tried fixing this by adding a "QuantityPanel" with a DefaultButton, but this doesn't solve my issue!
Any ideas?
My code:
<asp:Repeater ID="ProductBasketRepeater" runat="server"
onitemcommand="ProductBasketRepeater_ItemCommand"
onitemdatabound="ProductBasketRepeater_ItemDataBound1">
<ItemTemplate>
<tr class="BasketEntryItem">
<td class="ImageCol">
<asp:Image ID="ProductImageBox" runat="server" Width="50" />
</td>
<td class="NameCol">
<asp:HyperLink ID="ProductNameHyperlink" runat="server"></asp:HyperLink>
</td>
<td class="PriceCol">
<asp:Label ID="PriceLabel" runat="server"></asp:Label>
</td>
<td class="QuanCol">
<asp:Panel ID="QuantityPanel" runat="server" DefaultButton="UpdateQuantityBtn">
<asp:TextBox ID="QuantityBox" runat="server" Width="30px"></asp:TextBox>
<asp:LinkButton ID="UpdateQuantityBtn" runat="server" Text="Opdater" CommandName="UpdateQuantity"></asp:LinkButton>
</asp:Panel>
</td>
<td class="TotalCol">
<asp:Label ID="TotalPriceLabel" runat="server"></asp:Label><br />
<asp:Button ID="DeleteProductBtn" runat="server" Text="Slet" CommandName="Delete" />
</td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
</asp:Repeater>
In case jQuery is unavailable, you can use simple JavaScript to set to set default button for any texbox:
JS Code:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
ASPX page or any simple "input" textbox:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
Code begind C#:
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
Do you need help with apply this code in repeater ?
Using jQuery, this piece of code will issue a programmatic click when pressing enter in the textbox:
$('input[id$=QuantityBox]').keypress(function(e) {
if (e.keyCode == 13) {
$(this).next('input[id$=UpdateQuantityBtn]').click();
}
});
Note: I saw a bit late you did not requested jquery specifically, but in you do, this should do the trick.

Categories

Resources