How can i get the second list item value and assign to the textbox.For example my second list item is "edit profile" ,then after the textbox1 textchange, the textbox2 will auto assign "edit profile"
Here is my coding
<script language ="javascript" type="text/javascript">
$(document).ready(function () {
$("#TextBox1").bind('change', function (e) {
if ($("#TextBox1").val() != '') {
sendData();
}
});
function sendData() {
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "t1ViewDB.aspx" : loc;
$.ajax({
type: "POST",
url: loc + "/GetModuleList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d) {
//Get the second list item and assign value to textbox2
//???
$("#TextBox2").val('');
}
},
error: function () {
alert("An unexpected error has occurred during processing.");
}
});
}
});
</script>
backend code
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static ArrayList GetModuleList()
{
ArrayList listArr = new ArrayList();
listArr.Add(new ListItem("Dashboard"));
listArr.Add(new ListItem("Edit Profile"));
listArr.Add(new ListItem("Change Password"));
return listArr;
}
Just reference by index:
$("#TextBox2").val(msg.d[1]['Value'] );
Arraylist and webmethod
Related
I want to access cs function from js function in aspx page after the user click on Delete button. and send id to the cs function.
I try the below codes:
js
function deleteClick(ID) {
'<%Session["ID"] = "' + ID + '"; %>';
var x = '<%= Session["ID"] %>';
alert(x);
$.ajax({
type: "POST",
url: "AddPI.aspx/deleteClick",
//data: ' {ID:"' + ID + '"}',
data: JSON.stringify({ ID: "' + ID + '" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success");
},
failure: function (response) {
alert("Error");
}
});
}
cs
public void deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
}
}
the problem is the id can't be passed!
EDIT:
i solve the problem by change the cs function to static and edit the below field:
data: "{ ID: '" + ID + "'}",
that's it.
Now the problem is how to change the visibility of aspx div in a static cs function?
errorbox.Visible = false;
i got: Ann object reference is required for the non-static field....
i try call js on success
success: setVisibility,
and in the js:
$("#errorbox").hide();
but it does not works!
//Js Code
function deleteClick(ID) {
alert(ID);
$.ajax({
type: "POST",
url: "Default.aspx/deleteClick",
data: '{ID: "'+ID+'" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response,a,a2) {
alert("Not Done");
}
});
}
//c# Code
[System.Web.Services.WebMethod]
public static string deleteClick(string ID)
{
//Your Code
return null;
}
Noting your first issue is solved by you which is awesome! :)
and you have another problem in which you need to change the visibility of a div on error occurrence. Well you change the visibility of div errorbox to true as default value
errorbox.Visible = true;
and on your script section, hide this div using jquery:
$(function(){
$('[id$=errorbox]').hide(); //this will auto-run after page is completely loaded.
});
make little changes to your cs function such as:
public string deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
return "true"; //if successful
}
return "false"; //if not successful
}
and then if any error occurs on your ajax response(success/error) simply just do this in your ajax:
success: function (response) {
if(response.d == "true")
{
alert('success');
}
else{
$('[id$=errorbox]').show();
}
},
error: function (response) {
$('[id$=errorbox]').show();
}
On my web page I used jquery and ajax to call a C# function to fill Dropdown list with respect to another
Dropdown Branch is filled as per the selection of zone and Employee with the selection of branch.It works perfect But the button Click is not working after this.Someone please tell me why this button click is not working??
[Button click works when no drop down selection is made]
my Code look Like this:
Jquery
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= ddZone.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/BranchFill",
data: "{'Zone':'" + $("[id*=ddZone] option:selected").text() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlBranch = $("[id*=ddBranch]");
ddlBranch.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlBranch.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
$('#<%= ddBranch.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/EmployeeFill",
data: "{'Branch':'" + $(this).val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlEmployee = $("[id*=ddEmployee]");
ddlEmployee.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlEmployee.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
});
</script>
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object BranchFill(string Zone)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Branch = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch(Zone, "", "SelectBranch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Branch.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Code"].ToString()
});
}
return Branch;
}
else
{
return "false";
}
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object EmployeeFill(string Branch)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Employee = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch("", Branch, "SelectEmployee");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Employee Id"].ToString()
});
}
return Employee;
}
else
{
return "false";
}
}
And the button Click(which is not working)
protected void Button1_Click(object sender, EventArgs e)
{
ReportClass RC = new ReportClass();
if (ddZone.SelectedValue !="0")
{
RC.Zone = ddZone.SelectedValue;
RC.Branch = ddBranch.SelectedValue;
RC.EmployeeId = ddEmployee.SelectedValue;
Report = RC.GetReport();
}
}
Why this click function is not Working, please help me to know..
I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}
I have asp.net Gridview that have at least 15 rows with textbox by default example
aspx
<asp:GridView ID="gv_Others" runat="server" AutoGenerateColumns="false" CssClass="gvothers">
<Columns>
<asp:TemplateField >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate >
<asp:TextBox ID="txtEmp" runat="server" Width=100% Height=22px CssClass="txtE"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs (here how I am generating 15 rows of a GridView)
private void SetInitialRowsofOthers()
{
var list = new List<string>();
for (int i = 0; i < 16; i++)
{
list.Add(string.Empty);
}
gv_Others.DataSource = list;
gv_Others.DataBind();
gv_Others.HeaderRow.Visible = false;
}
WevService.axms
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetotherServices(string txt1)
{
// your code to query the database goes here
List<string> result = new List<string>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["autoDBConn"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like #SearchText + '%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", txt1);
SqlDataReader obj_result1 = obj_Sqlcommand.ExecuteReader();
while (obj_result1.Read())
{
result.Add(obj_result1["txt1"].ToString().TrimEnd());
}
}
}
return result;
}
I want to fill each textbox by jQuery autocomplete.. for this I created a webservice and getting a value from jQuery.
How I am trying to achieve this task:
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
$($arrT).autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetotherServices",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
$("#<%=Txt_RegNo.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt' : '" + $("#<%=Txt_RegNo.ClientID %>").val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
</script>
<script type="text/javascript">
function Load_OtherService() {
var hv = $('input[id$=hdnOthers]');
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
var hv1 = "" + hv.val();
var va = hv1.split(',');
for (var j = 0; j < va.length; j++) {
var $txt = $arrT[j];
$($txt).val(va[j]);
}
}
</script>
Now for example when I type "Engine Work" in TEXTBOX 1 and select the value which populated by jQuery autocomplete("Engine Work") then second time when I type in other text box (TEXT BOX 2). It's only give me the "Engine Work" option to select.. which means after selecting any value (populated by jQuery autocomplete) I can't select any other value in other text boxes....
Example:- (See Image Below)
as you see i type Genral Work but still it`s populating the Previous value "Engine Work" in jquery AutoComplete which i dont want
How to find the TextBox by CSS Class using jQuery????
Something like this (its only find TextBox id by using jQuery inside GridView but I need to find textbox by Css Class)
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
Change your script block to this:
$(document).ready(function() {
// This selects all inputs inside the table with the txtE class and applies
// the autocomplete function to them
$('table[id$="gv_Others"] input.txtE').autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + request.term + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
});
Look at the data: in the ajax post - it's using request.term and I changed the selector.
The issue with your jquery is this line:
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
That will always return the first value of the array (the first textbox) so it's always submitting the first value to your webservice as the search text.
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace PlatForm_RollUp
{
/// <summary>
/// Summary description for SearchDPN
/// </summary>
public class SearchDPN : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
if (string.IsNullOrEmpty(prefixText)) { prefixText = "NA"; }
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["PPN_ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select DPN_Key, DPN, Item_Desc from Customer.DIM.PPN WHERE " +
"DPN like #SearchText+'%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
//StringBuilder sb = new StringBuilder();
List<string> _dpn = new List<string>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//sb.Append(string.Format("{0} - {1}", sdr["DPN"], sdr["Item_Desc"], Environment.NewLine));
_dpn.Add(sdr["DPN"].ToString() +" - " +sdr["Item_Desc"].ToString());
}
}
conn.Close();
context.Response.Write(new JavaScriptSerializer().Serialize(_dpn));
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
***************************
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
initializer();
});
var prmInstance = Sys.WebForms.PageRequestManager.getInstance();
prmInstance.add_endRequest(function () {
//you need to re-bind your jquery events here
initializer();
});
function initializer() {
$("[id*=txtDPN]").autocomplete({ source:
"/Handlers/SearchDPN.ashx" });
}
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var LastRecID = 1;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
var ImpData = document.getElementById('<%= hdnLanguage.ClientID %>').value;
if (LastRecID <= 1)
sendData();
LastRecID++;
}
});
function sendData() {
$.ajax(
{
type: "POST",
url: "try.aspx/GetData",
data: ImpData ,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "true",
success: function (msg) {
$("#myDiv").append(msg.d);
},
Error: function (x, e) {
alert("err");
}
});
}
});
</script>
I have hidden Field and it has same value. I set ImpData for hdnLanguage
var ImpData = document.getElementById('<%= hdnLanguage.ClientID %>').value;
I send data with Json:
data: ImpData
But I dont know how to call this data (ImpData) on code behind(in static web service). Thanks for your answer.
The data are translated to the GetData parameters. You if you send data like this:
data: { param1: ImpData }
Your GetData method has to have at least the param1 parameter:
public static void GetData(string param1)
I find answer
Json:
data: "{'Param': '" + Param + "'}"
Code Behind:
public static string GetData(string Param)
{
....
}