clear the labels text value - javascript

<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Script2.aspx.cs" Inherits="Javascript.Script2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="javascript" type="text/javascript">
function ClearValue(Text1, Text2) {
var txtClear1 = document.getElementById(Text1);
var txtClear2 = document.getElementById(Text2);
if (txtClear1 != null || txtClear2 != null)
{
txtClear1.outerText = "";
txtClear1.value = "";
txtClear1.innerText = "";
txtClear1.innerHTML = "";
txtClear1.outerHTML = ""
txtClear2.value = "";
txtClear2.innerText = "";
txtClear2.innerHTML = "";
txtClear2.outerHTML = ""
return false;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblError1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="lblError2" runat="server" Text="Label2"></asp:Label>
<asp:Button ID="btnClose" runat="server" Text="Button"
onclick="btnClose_Click" />
</div>
</form>
</body>
</html>
namespace Javascript
{
public partial class Script2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnClose.Attributes.Add("onclick", "ClearValue('" + lblError1.ClientID + "','" + lblError2.ClientID + "')");
}
protected void btnClose_Click(object sender, EventArgs e)
{
}
}
}
here iam not able to clear the text value of Label .
once i clcik the button.here i am trigerring the function to clear the labels values.
but the text is not getting cleared.
any idea how to solve the issue.
thanks.

The ID of an ASP.NET control is not the same as the id in the DOM. The HTML element's ID is generated by ASP.NET at runtime.
You can specify the DOM id by specifying the ClientID attribute:
<asp:Label ID="lblError1" ClientID="lblError1" runat="server" Text="Label1"></asp:Label>

It seems that labels are not suitable for this purpose. Labels changed client-side do not keep their values on PostBacks. use a textbox instead and make it look like a label by setting borderwidth=0
<asp:TextBox ID="lbl_error" BorderColor="White" BorderStyle="None" BorderWidth="0" runat="server" Width="99%"></asp:TextBox>
then in javascript write this function
function resetlabel() {
document.getElementById("<%=lbl_error.ClientID%>").value = "";
}

Related

Cannot get filename from AjaxFileUpload using javascript and asp.net

I've tried solving this out and researching for weeks and i still can't get it to work. My code is to simply upload images and then save it in the database without postback.
As of now, I used AjaxFileUpload to upload images. My plan was to get the uploaded filename in AjaxFileUpload using javascript and then store it in a hiddenfield. And then when the admin clicks submit, it will get the value that was stored in the hiddenfield and then save it in the database(using the query that i have created in my code-behind).
The problem is, it will always return empty. I hope you guys can really help me on this one.
Here is the code for the aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="asp"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Music Store</title>
<script src="../Javascript/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="~/Styles/jquery.bxslider.css"/>
<link rel="shortcut icon" type="image/png" href="~/Images/rockSign.png"/>
<script type="text/javascript">
function abc() {
var elem1 = document.getElementById('<%# itemFileUpload1.ID %>').value;
document.getElementById('HiddenInput1') = elem1;
var elem2 = document.getElementById('<%# itemFileUpload2.ID %>').value;
document.getElementById('HiddenInput2') = elem2;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="wrapper">
<h1>Item Image1:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload1" runat="server"
Width="300px" OnUploadComplete="itemUploadImage1"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput1" name="HiddenInput" value="" />
<h1>Item Image2:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput2" name="HiddenInput" value="" />
<br/>
<asp:Label ID="lblResult2" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" CssClass="submitButton"
Text="Save Item" OnClick="Button1_Click"/>
</div>
</form>
</body>
</html>
And here is the code for the aspx.cs:
protected void itemUploadImage1(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void itemUploadImage2(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
string item_image1 = Request.Form["HiddenInput1"];
string item_image2 = Request.Form["HiddenInput2"];
ConnectionClassGuitarItems.AddStringInstrumentItems(item_image1,item_image2);
lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2;
ClearTextFields2();
}
catch (Exception ex)
{
lblResult2.Text = ex.Message;
}
}
Notice the the Button1_Click, I try to access the value of HiddenInput1 and HiddenInput2 but it seems like they are empty.
Why not use a regular asp:FileUpload control and wrap part of your form/code block in an updatepanel to achieve the same desired action as using a AjaxFileUpload control:
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPnlName">
<ContentTemplate>
<asp:FileUpload runat="server" ID="fileImport" CssClass="form-control"/>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void btnUpload_OnClick(object sender, EventArgs e)
{
if (fileImport.HasFile)
{
UploadProcessFile();
}
}
private void UploadProcessFile()
{
var fileName = fileImport.FileName;
//Process the rest of your code below you can also assign the file name to your textbox.
}
You can get your image name like this on aspx file on
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
use this script
function abc(sender, args) {
var Imagename = args.get_fileName();
alert(Imagename );
}
this way is very simple hope this help you

ASP.NET to have a text field in confirm window and use required field check for that

i am having a confirm window show in ASP.NET when clicking on a button and i do this in C# as below,
ScriptManager.RegisterStartupScript(this, typeof(string), "confirm", "ConfirmAccept();", true);
Then the confirm function is called in JavaScript as below,
function ConfirmAccept() {
if (confirm("Do you confirm to add this entry?")) {
var clickButton = document.getElementById("<%= button_add.ClientID %>");
clickButton.click();
}
}
Here when i click on the button and confirm box comes and when i press ok the code inside the button_add click is executed. But here i want to have a text box to show up in the confirm window and i want the enter a value before clicking OK on confirm box. This field should also have a required field check on clicking the OK button. Then after clicking OK i want to access this field's value or text inside the button_add click event. How can i do that?
i think you want this code..
If you do not want this.
i am so sorry.
my english skill is low.
.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
function ConfirmAccess() {
var result = prompt("Do you confirm to add this entry?", "");
if (result == null) {
alert("click cancel");
return false;
}
alert("you enter this value : " + result);
var hidConfirmValue = document.getElementById("<%=hidConfirmValue.ClientID%>");
hidConfirmValue.value = result;
var clickButton = document.getElementById("<%= btnAdd.ClientID %>");
clickButton.click();
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField runat="server" ID="hidConfirmValue" />
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClientClick="return ConfirmAccess();"/>
<asp:Button runat="server" ID="btnAdd" Text="Add" OnClick="btnAdd_Click" />
<asp:TextBox runat="server" ID="txtResult"></asp:TextBox>
</div>
</form>
</body>
</html>
.cs
using System;
namespace StackoverflowWebForm
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
txtResult.Text = hidConfirmValue.Value;
}
}
}

Add client side handler from content page to master page control

I have a requirement for four similar pages in an ASP.Net webforms application. All four pages will have a header with a dropdown and two buttons. I intend to use a master page for this header and then content pages for each of the different pages I need to produce. My master looks like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Processing.master.cs" Inherits="MyProject.Processing" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="../../Stylesheets/Processing.css" type="text/css" rel="stylesheet" />
<script language="javascript" src="../../Scripts/js/Processing.js" type="text/javascript"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="ProcessingForm" height="100%" runat="server">
<asp:Label ID="titleLabel" runat="server" class="bold"></asp:Label>
<asp:Label runat="server" ID="storeLabel" Text="Store:" />
<asp:ObjectDataSource runat="server" ID="storesDataSource" TypeName="MyProject.Processing"
SelectMethod="GetStoresDataSource">
<SelectParameters>
<asp:QueryStringParameter Name="UserName" QueryStringField="eUserName" DefaultValue="" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:DropDownList runat="server" ID="storeDropdown" AutoPostBack="true" OnSelectedIndexChanged="storeDropdown_SelectedIndexChanged"
AppendDataBoundItems="true" DataSourceID="storesDataSource" DataTextField="Display"
DataValueField="Number">
<asp:ListItem />
</asp:DropDownList>
<asp:Button ID="refreshButton" runat="server" Text="Refresh" OnClick="refreshButton_Click" />
<%-- ************************************************************************************--%>
<%-- This is the button that I want to add client side behaviour to from my content pages--%>
<%-- ************************************************************************************--%>
<asp:Button ID="processButton" runat="server" Text="Process" OnClick="processButton_Click"
OnClientClick="DoStuff();" />
<asp:ContentPlaceHolder ID="GridDiv" runat="server" />
</form>
</body>
</html>
In the Processing.master.cs I've defined an event that the content pages can subscribe to to react when the dropdown changes:
public delegate void StoreChangedHandler(object sender, string selectedValue);
public event StoreChangedHandler OnStoreChanged;
protected void storeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (OnStoreChanged != null)
{
OnStoreChanged(sender, ((DropDownList)sender).SelectedValue);
}
}
So the content page's OnLoad contains:
protected void Page_Load(object sender, EventArgs e)
{
((Processing)Master).OnStoreChanged += StockRoomWithMaster_OnSomethingSelected;
}
void StockRoomWithMaster_OnSomethingSelected(object sender, string selectedValue)
{
this.stockReceiptGridView.DataBind();
}
What is the best way to do this same strategy for the client side DoStuff() function call that occurs when the processButton control is clicked? I could declare a global variable in the Processing.js file and in the content page assign it to a function:
Processing.js:
var processButtonClickedHandler;
function DoStuff()
{
if (processButtonClickedHandler) {
processButtonClickedHandler();
}
}
In content page:
$(document).ready(function() {
processButtonClickedHandler = DoSpecificStuff;
});
function DoSpecificStuff() {
// Custom page client side stuff
}
I think the way you are doing this is the best way. I have created created a test bu putting an alert in DoSpecificStuff in the same way you did and it worked good.

Get me off the JavaScript postback Failboat

I've got to call two js functions, setfocus on textbox and stop a postback from occuring on single buttonclick. I think I got it if I could only intercept the postback. My js skills are on par with weaksauce.
test case
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="JsTextFocus.aspx.cs" Inherits="WebApplication1.JsTextFocus" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="Javascript">
function aMethod() {
var dowork = 'bleh';
}
function setFocusOnTextBox() {
TextBox1.Focus();
return false;//Stop the postback..FAIL
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="imageBtn" runat="server" ImageUrl="images/document_Small.gif" CausesValidation="false" OnClientClick="aMethod();return setFocusOnTextBox();return false;" />
</div>
</form>
</body>
</html>
Page load shouldn't fire after OnClientClick
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("PS happened at " + DateTime.Now);
}
You are referring to TextBox1 in yout setFoucs.. function which is unknown at that point. Use document.getElementByID to get a reference to textbox and then call focus not Focus.
function setFocusOnTextBox()
{
var TextBox1 = document.getElementById("TextBox1");
TextBox1.focus();
return false;
}
You can remove the return false at the end of the Image ClientClick handler.
i.e.:
<asp:ImageButton ID="imageBtn"
runat="server"
ImageUrl="images/document_Small.gif"
CausesValidation="false"
OnClientClick="aMethod();return setFocusOnTextBox();" />

Adding Input control to the pages with jQuery has problem with HttpFileCollection in ASP.NET

I'm trying to add upload controls to the page.
This HTML mark-up with JavaScript is working fine but there
s no option to remove the added control:
1. Example A
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Multi File Upload</title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p id="upload-area">
</p>
<input id="AddFile" type="button" value="Add file" onclick="addFileUploadBox()" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />
<script type="text/javascript">
function addFileUploadBox() {
if (!document.getElementById || !document.createElement)
return false;
var uploadArea = document.getElementById("upload-area");
if (!uploadArea)
return;
var newLine = document.createElement("br");
uploadArea.appendChild(newLine);
var newUploadBox = document.createElement("input");
// Set up the new input for file uploads
newUploadBox.type = "file";
newUploadBox.size = "60";
// The new box needs a name and an ID
if (!addFileUploadBox.lastAssignedId)
addFileUploadBox.lastAssignedId = 100;
newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId);
newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId);
uploadArea.appendChild(newUploadBox);
addFileUploadBox.lastAssignedId++;
}
</script>
</form>
</body>
</html>
1. Example A : the code behind
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim sfile As String
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)
Try
uploads(i).SaveAs("C:\UploadedUserFiles\" + c)
sfile += uploads(i).FileName & "<br/>"
Span1.InnerHtml = "File Uploaded Sucessfully."
Catch Exp As Exception
Span1.InnerHtml = "Some Error occured."
End Try
End If
Next i
Label1.Text = sfile
End Sub
2. Example B with jQuery and option to "Remove" added control
However when I changed JavaScript to jQuery, it doesn't work. I can add and remove control but when I submit no files are uploaded. Mark-up with jQuery:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="add-remove-control.aspx.vb"
Inherits="APIU.Web.add_remove_control" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="_Assets/scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var i = 1;
//allow only 3 elements
$('#add').click(function() {
if (i < 4) {
var add_input = '<input type="file" id="' + 'dynamic:' + i + '" name="' + 'dynamic:' + i + '" />
var add_link = 'Remove'
$('body').append('<p>' + add_input + add_link + '</p>');
i++;
}
});
$('.remove').live('click', function() {
$(this).parent('p').remove();
i--;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Add
<input id="File1" type="file" runat="server" size="60" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<p>
</p>
</div>
</form>
</body>
</html>
2. Example B: the code behind:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim sfile As String
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)
Try
uploads(i).SaveAs("C:\UploadedUserFiles\" + c)
sfile += uploads(i).FileName & "<br/>"
Catch Exp As Exception
End Try
End If
Next i
End Sub
Every thing was working fine with Example A, only there's no option to remove the added contorls.When I added "Remove" control option with jQuery in Example B, HttpFileCollection can't get any file from input control added to the page.
In your Example A, in the form tag has enctype="multipart/form-data">
<form id="form1" runat="server" enctype="multipart/form-data">
but there's no enctype property in Example B,
<form id="form1" runat="server">
Here's a reference on MSDN and a question about enctype property on asp.net forum.
If you need to only set form property of enctype to a specific page only, in case you are using master page, you can set property to that page like this:
If Not Page.IsPostBack() Then
Me.Form.Enctype = "multipart/form-data"
End If
Cheer. :D

Categories

Resources