How to call javascript function from asp:textbox? - javascript

I am using textbox for searching items from data base and loading them in gridview and
i used custom paging on gridview to show only 25 records per page
and i found java script for searching records on client side as
script>
function filter2(phrase, _id) {
var words = phrase.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var ele;
for (var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
var displayStyle = 'none';
for (var i = 0; i < words.length; i++) {
if (ele.toLowerCase().indexOf(words[i]) >= 0)
displayStyle = '';
else {
displayStyle = 'none';
break;
}
}
table.rows[r].style.display = displayStyle;
}
}
</script>
and calling this as:
<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>
this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox
but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')"event in my asp textbox e-g
<asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" runat="server" AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />
but asp didn't allow me to do that..
i need your help to achieve this.
thanks in advance.
EDIT:
I need both searching (client side, server side) in single textbox
because
client side allow searching from loaded page of gridview and
server side allow searching from database on clicking

You could add the client attribute of rendered input control via code behind:
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}
EDIT:
After the right comment of #Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:
<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.
For example:
<asp:Label runat="server" ID="label">test</asp:Label>
<asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>
This is what we have in output:

Related

Call Javascript Function From Server Side C#

I created a report that shows a list of manifests. The user can search through this list by the manifest number. When the code is running the search, I'm displaying a Gif:
But this Gif won't disappear once the search is finished. I can see the correct record is being displayed so the search is over, but the Gif stays on the screen.
The function is called when the search button is clicked.
<asp:Button runat="server" CssClass="btnSearch loading" ID="btnSearch" Text="Search" OnClick="btnSearch_Click" OnClientClick="ShowLoadingGif()" ToolTip="Search" />
<div id="dvLoading">
<table>
<tr>
<td id="tdLoadingSave"><img src="/images/loading.gif" alt="Loading..." title="Loading..." /></td>
</tr>
</table>
</div>
function ShowLoadingGif() {
closefiltermenu();
$("#tdLoadingSave").html($("#tdLoadingSave").html() + "<br/> Please wait, manifest list is loading");
$('#dvLoading').fadeIn("500");
}
function CloseLoadingGif() {
$('#dvLoading').fadeOut("500");
}
The search is then run from another function:
protected void Search()
{
string Field = ddlSearchBy.SelectedValue;
string SearchString = txtSearchBy.Text;
string[] SearchFields = null;
string[] SearchStrings = null;
if (!string.IsNullOrEmpty(SearchString) && Field != "null")
{
SearchFields = new string[] { Field };
SearchStrings = new string[] { SearchString };
}
List<lookupManifestAnalysis> main = lookupManifestAnalysis.SearchManifestItems(Company.Current.CompanyID,
SearchStrings,
SearchFields);
gvResults.DataSource = main;
gvResults.DataBind();
udpResults.Update();
ClientScript.RegisterStartupScript(GetType(), "Search", "CloseLoadingGif();", true);
}
But how do I stop the Gif displaying once the search is over?
ScriptManager.RegisterStartupScript(this, GetType(), "CloseLoadingGif","CloseLoadingGif();", true);
OR
If you are dealing with asp.net UpdatePanel and UpdateProgress, use the following code:
ScriptManager.RegisterStartupScript(myUpdatePanelID,myUpdatePanelID.GetType(),"CloseLoadingGif", "CloseLoadingGif();", true);
When you are executing your code in Server side ASP you should not use client side function for showing or hiding elements. Instead try using Ajax Controls from .Net.
You will need to use AJAX Progress control. Here have a look :
https://msdn.microsoft.com/en-us/library/bb386421.aspx

Show Modal Dialog/Confirmation Box Based on User Input in Code Behind/ASP.net

I have a grid view consisting of a text box and drop down for every row in the grid view. I want a confirmation dialog to show when the user enters a value in the text box if it does not match the value of a corresponding label for each row in which this is true.
Front End
<asp:TemplateField HeaderText="Payment Amount">
<ItemTemplate>
<asp:Label ID="lblSuggestedAmount" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actual Payment Amount">
<ItemTemplate>
<asp:TextBox ID="txtbxActualAmount" Visible="true" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="For Rental Month">
<ItemTemplate>
<asp:DropDownList ID="ddlPaymentMonth" Visible="true" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
What I found to work on my local machine when debugging was System.Windows.Forms.MessageBox.Show() but when I upload my project to my IIS the prompt does not appear.
Code Behind
TextBox actualAmount = (TextBox)gvPayments.Rows[i].FindControl("txtbxActualAmount");
Label suggestedAmount = (Label)gvPayments.Rows[i].FindControl("lblSuggestedAmount");
if (Convert.ToDouble(actualAmount.Text) != Convert.ToDouble(suggestedAmount.Text)) {
System.Windows.Forms.DialogResult dr = System.Windows.Forms.MessageBox.Show("Some payments have actual payment amounts greater than the suggested amount. Is this correct?", "Warning",
System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Warning,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
System.Windows.Forms.MessageBoxOptions.ServiceNotification);
if (dr == System.Windows.Forms.DialogResult.No) {
return;
} else {
actualAmount.BackColor = Color.White;
}
}
I understand that because the dialog shows up on client side, where the code is run that the dialog is showing up on the server, and not on the clients browser.
From reading other similar questions I also understand I need to achieve this with JavaScript.
I imagine I will attach an OnClick event to my update/submit button but will the javascript be able to cycle row through row of my gridview, compare the Label.text and the TextBox.Text and set that text boxes background color to yellow and display my dialog? And then will it know to continue with the rest of the code-behind execution once the user has clicked ok?
First of all, you can't use Windows.Forms on asp.net application, remember that the UI is running in the browser of the client computer, the code behind that you write is running on the server side, in different computer...
You have 2 options to achieve the goal:
Short way, bad performance: Add javascript function to the end of the response, the javascript will show confirmation box in the browser, but all the logic still written in code behind, this is done by calling to
ClientScript.RegisterClientScriptBlock
RegisterClientScriptBlock(this.GetType(),
"confirmmsg",
"<script> if(Confirm('do you want to proceed')) forms.submit();</script>");
Long and best way, javascript & jquery can easily implement the code you need, for example:
function checkText(txt) {
var allLables = $("[id*='lblSuggestedAmount']"); //get all the labels in the grid
for (var i = 0; i < allLables.length; i++) {
if (allLabels[i].html() == txt) {
txt.style.bakground-color = "yellow";
if(Confirm("This is message to confirm")) {
form1.submit() // what ever you need
}
}
}
}
Firstly in the front end I did add some JavaScript/jQuery that the other answer provided.
Front End
<script>
// not sure exactly how much of this I need but here goes!
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = "no";
$(document).ready(function () {
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = "no";
});
function confirmPayment() {
var allLabels = $("[id*='lblSuggestedAmount']");
var allTextBoxes = $("[id*='txtbxActualAmount']");
var failFlag = false;
for (var i = 0; i < allLabels.length; i++) {
if (allTextBoxes[i].value != "" && parseFloat(allLabels[i].innerText) != parseFloat(allTextBoxes[i].value)) {
failFlag = true;
}
}
if (failFlag) {
if (confirm("Some payments have actual payment amounts that are different from the suggested amount. If this is correct, click Ok, if not click Cancel.")) {
confirm_value.value = "yes";
document.forms[0].appendChild(confirm_value);
} else {
confirm_value.value = "no";
document.forms[0].appendChild(confirm_value);
}
}
}
</script>
and in my asp:Button that also fires the code-behind
<asp:Button ID="btnUpdateClient" Text="Update Client" OnClientClick="confirmPayment()" OnClick="btnUpdateClientTable_Click" Visible="true" runat="server" />
Back End
In my btnUpdateClientTable_Click() method
I needed
string confirm = Request.Form["confirm_value"];
bool paymentErrorFlag = false;
to get the response to the confirm dialog. This would house a "yes" or "no" response. The flag would get set to true whenever a value was input in the text box but a value was not selected from my drop down list.
I would cycle through every row in the grid view and using a combination of the paymentErrorFlag and checks on .Text == string.Empty and .SelectedIndex == 0 to break the function and return; without updating the database.
Essentially the key was the Request.Form[] returning the value of the selection in the confirmation dialog.

Inject JavaScript to a link button from code behind in c#

Good day,
I have a repeater that contain link button. The value and number of link button is generate base on data pull from database. The HTML code is something as follow:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
Here is some code that I try to do in my code behind,
for (int i = 0; i < table.Rows.Count; i++)
{
RepeaterItem itm = repCategories.Items[i];
GiftRow dr = tbl.GetRow(i);
Literal litLink2 = (Literal)itm.FindControl("litLink2");
litLink2.Text = dr.Name;
string myScript = string.Empty;
myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
}
By doing this, I will get alert hi when I load the page.What I want to do is, I only want it do alert hi when I click on the link button, instead of page load.
Use a LinkButton and leverage the ClientClick event instead:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
<asp:LinkButton ID="lbMyLinkButton" runat="server" />
</ItemTemplate>
</asp:Repeater>
I'd also recommend you use ItemDataBound events of repeaters where possible:
void repCategories_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((LinkButton)e.Item.FindControl("lbMyLinkButton")).OnClientClick = "alert('hi');";
}
}
NOTES:
I wouldn't ever recommend you render javascript server-side unless absolutely necessary. I've provided an answer to fit in with the context of your question, but I would advise you have a javascript function already on your page and 'wire it up' server-side (if not bind it on the client with pure javascript)
There is also an assumption here that you're binding data to the repeater (you should be anyway), which means you also have to wire up the ItemDataBound handler: repCategories.OnItemDataBound += repCategories_ItemDataBound

Adding items to a ListBox without scrolling up

I have a ListBox that contains all the online users.
The users are loaded from a MySQL database and loaded into the ListBox every second.
When I add an Item to the ListBox the ListBox scrolls up, I do not want this to happen.
<asp:UpdatePanel ID="usersPanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListBox ID="lstUsers" runat="server" ViewStateMode="Enabled" AutoPostBack="True"></asp:ListBox>
<asp:Timer ID="mainTimer" runat="server" ontick="Timer1_Tick" Interval="1000"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Timer Code:
protected void Timer1_Tick(object sender, EventArgs e)
{
...
MySqlDataReader datareader = command.ExecuteReader();
if (datareader.HasRows) {
lstUsers.Items.Clear();
while (datareader.Read()) {
lstUsers.Items.Add(new ListItem(datareader.GetString(1), datareader.GetInt32(0).ToString()));}
}
}
I've tried to do it with javascript but I was unable to get/set the scrollbar position on the listbox
What is done here is to save the current selected on list on client side, and set it back after the panel have been updated with the new values.
<script type="text/javascript" language="javascript" >
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beighnloadinf);
prm.add_endRequest(EndRequest);
var selected = "";
//get selected index and store in variable
function beighnloadinf() {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
var listLength = sel.options.length;
for(var i=0;i<listLength;i++){
if(sel.options[i].selected){
selected =sel.options[i].value;
break;
}
}
}
// set selected index back afrer update finished
function EndRequest(sender, args) {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
sel.value = selected;
}
</script>
You can do the same thing and on code behind, you get the selected one, and place it after the new update of your list.
You shouldn't be clearing the control every second. This is your problem:
lstUsers.Items.Clear();
Simplest solution would be to compare you ListBox items with your data source using the Except method on IEnumerable.
You'll have to convert your data source to IEnumerable manually. See this post as to how to do that.
NOTE: You'll have to change the type for the extension method.
After that, you can loop through your difference set (the returned object for .Except()) and add them to your list box like this:
lstUsers.Items.Add("a new list item");

How can I access to an HTML control runat server from javascript

I have the following code:
<telerik:GridTemplateColumn DataField="JOB_CODE"
<EditItemTemplate>
<input type="text" ID="JOB_CODETextBox" runat="server"
value='<%# Eval("JOB_CODE") %>' readonly="readonly"
onclick="$('#basic-modal-content').modal({
appendTo:'form', persist: true,
onClose: function (dialog)
{
/*
I want to assign here a value to the textbox control
like this: JOB_CODETextBox = 'something...'
I tried this:
$find('<%= JOB_CODETextBox.ClientID %>').value = 'something..'
but it didn't work!! the find function returns [null]
*/
$.modal.close();
}
} );" />
Any help!!
This should work:
$('#'+'<%= JOB_CODETextBox.ClientID %>').val('something');
or (C# only):
$('<%= "#" + JOB_CODETextBox.ClientID %>').val('something');
or using JavaScript/ECMAScript:
document.getElementById('<%= JOB_CODETextBox.ClientID %>').value = 'something';
I'm not familiar with the telerik control you are using so I'm going to assume it's similar to other databound controls. Operating with that in mind, here is an example using a Repeater control.
here's the markup
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
<input type="text" id="JOB_CODETextBox" runat="server" />
</ItemTemplate>
</asp:Repeater>
in this situation, I usually generate the javascript server side.
System.Text.StringBuilder js = new StringBuilder();
js.AppendLine(" <script>");
// we'll store all the control references in a list
// since there will be one for each item in the repeater
js.AppendLine(" var JOB_CODETextBox_list = [];");
for (int j = 0; j < this.rpt1.Items.Count; j++)
{
System.Web.UI.HtmlControls.HtmlGenericControl JOB_CODETextBox;
// try to locate the copy of the control local to each item
JOB_CODETextBox = (HtmlGenericControl)this.rpt1.Items[j].FindControl("JOB_CODETextBox");
if (JOB_CODETextBox != null) // make sure you found something
{
js.AppendFormat("JOB_CODETextBox_list.push(document.getElementById('{0}'));", JOB_CODETextBox.ClientID);
js.AppendLine();
}
}
js.AppendLine(" </script>");
this.Page.ClientScript.RegisterStartupScript(typeof(Page), "JOB_CODE", js.ToString(), false);
that should generate a script that gets a reference to all instances of that input control within the Repeater. after it runs, you can access the items client side like
JOB_CODETextBox_list[n].value = 'something';

Categories

Resources