I need an auto complete textbox. I tried the following code segment:
<input type="text" id="tbx_srchByFn" class="autosuggest" disabled="disabled" value="fieldname" runat="server"
onclick="this.value=''" />
jquery
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "DDL_Home.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('tbx_srchByFn').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
.cs file
using System.Web.Services;
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("constr"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Name from Register where Name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}
}
when I type on text box i didn't get the output.but when I remove runat="server" it works. I just need that in server so that I can take the textbox value from serverside
when I remove runat="server" it works.
I think postback happening in your code. so you must rebind SearchText() function. Add the following javascript in your code.
Try this code :
var prm_lp = Sys.WebForms.PageRequestManager.getInstance();
//Re-bind for callbacks
prm_lp.add_endRequest(function () {
SearchText();
});
Related
I am facing a problem while making an autocomplete textbox in asp.net with javascript and c#
The problem is that nothing is working if I include the links to /bootstrap.css and /vendors.min.js on my page.aspx.
If I remove those then everything works fine.
I cannot remove that link and script because my full project is depending on them. Can anyone please help me to solve this?
These are the tags I've added:
<link rel="stylesheet" type="text/css" href="/app-assets/css/bootstrap.css"/>
<script src="/app-assets/vendors/js/vendors.min.js"></script>
This is my Script:-
<script type="text/javascript">
$(function() {
$("#textbox").autocomplete({
source: function(request, response) {
var param = {
name_details: $('#textbox').val()
};
$.ajax({
url: "Page.aspx/Get_Names",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function(data) {
return data;
},
success: function(data) {
response($.map(data.d, function(items) {
return {
value: items
}
}))
},
});
},
minLength: 1
});
});
</script>
this is my c# Code:
[WebMethod]
public static List<string> Get_Names (string name_details)
{
String Command_Query = System.Configuration.ConfigurationManager.AppSettings["SP_Product_Name_Search"].ToString();
List<string> Product_names = new List<string>();
String MasterConnection = System.Configuration.ConfigurationManager.AppSettings["Connectionstring"].ToString();
SqlConnection con = new SqlConnection(MasterConnection);
string sqlqry = string.Format(Command_Query + " '{0}'", name_details);
con.Open();
SqlCommand command = new SqlCommand(sqlqry,con);
SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
Product_names.Add(sdr.GetString(0));
}
con.Close();
return Product_names;
}
I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.
<body>
<h3 id="apply-to-multiple-textareas">Apply to Multiple Textareas</h3>
<div class="textarea-wrapper">
<textarea class="textarea4 form-control" rows="4"></textarea>
</div>
<div class="textarea-wrapper">
<textarea class="textarea4 form-control" rows="4"></textarea>
</div>
</body>
<script type="text/javascript" class="brush: js; script" >
$('.textarea').textcomplete([
{ // tech companies
words: [],
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con4=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital","root","root");
String vsql4 ;
try
{
Statement st4=con4.createStatement();
vsql4="select hi from new1";
ResultSet Rs4=st4.executeQuery(vsql4);
while(Rs4.next())
{
%>
words.push("<%= Rs4.getString("hi") %>");
<%
}
%>
match: /\b(\w{2,})$/,
search: function (term, callback) {
callback($.map(this.words, function (word) {
return word.indexOf(term) === 0 ? word : null;
}));
},
index: 1,
replace: function (word) {
return word + ' ';
}
}
]);
</script>
I tried this but not getting result is something wrong here i am new in javascript i am going to autocomplate my textarea it works on words: ['apple', 'google', 'facebook', 'github'], but when I retrieve it from db not getting result
Check this, it may help you
<head id="Head1" runat="server">
<title></title>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetData",
data: "{'DName':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error......");
}
});
}
});
});
</script>
</head>
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetData(string DName)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SYSTEM-30;database=DB_Test_Trainees;user id=test;password=Test"))
{
using (SqlCommand cmd = new SqlCommand("select Dname from DEPTDHII where Dname like '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", DName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["DName"].ToString());
}
return result;
}
}
}
}
have a look on this site -> http://www.c-sharpcorner.com/UploadFile/29d7e0/jquery-autocomplete-getting-data-from-database-in-Asp-Net/
## Regarding autocomplete textbox ##
In below code i want autocomplete textbox first search from database ,if data not find from database then search from google api in asp.net, but in this case search data from databae and google api.
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$('#Address').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Root.aspx/GetAutoCompleteData",
data: "{'Address':'" + document.getElementById('Address').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
if (response(data.d) == null) {
var svalue = /** #type {HTMLInputElement} */(document.getElementById('Address'));
var svalueBox = new google.maps.places.SearchBox(/** #type {HTMLInputElement} */(svalue));
}
},
error: function (result) {
alert("Error");
}
});
}
});
});
<input id="Address" type="text" style="width: 305px" placeholder="From..."/>
[WebMethod]
public static List<string> GetAutoCompleteData(string Address)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Address from Locations where Address LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", Address);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Address"].ToString());
}
return result;
}
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var data = {};
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//google.maps.event.addDomListener(window, 'load', InitializeMap);
function InitializeMap() {
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
var latlng = new google.maps.LatLng(21.7679, 78.8718);
var myOptions =
{
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var svalue = /** #type {HTMLInputElement} */(document.getElementById('<%=txtSearch.ClientID %>'));
var svalueBox = new google.maps.places.SearchBox(/** #type {HTMLInputElement} */(svalue));
}
$(document).ready(function () {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
debugger
$.ajax({
url: '<%=ResolveUrl("~/bw.aspx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
debugger
if (data.d.length == 0) {
$('.ui-autocomplete').hide();
InitializeMap();
}
else {
$(".pac-container").remove();
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
}
},
error: function (response) {
debugger
alert(response.responseText);
},
failure: function (response) {
debugger
alert(response.responseText);
}
});
},
select: function (e, i) {
debugger
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
},
minLength: 1
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</form>
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Address,LocationID from Locations where " + "Address like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["Address"], sdr["LocationID"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
I am new on Ajax. I need to find how to list autocomplete results as a link. When user clicks the result should open that link. I can list the related result but I couldn't find how to add the links. It should be added somewhere in the script as a html tag. Please give me some clue how to add html link
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'question':'" + document.getElementById('txtQuestion').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
Here is the method which connects to the db and returns related results:
[WebMethod]
public static List<string> GetAutoCompleteData(string question)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx+"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Questions,Link FROM DigiQA WHERE Questions LIKE '%'+#quest+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#quest", question);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Questions"].ToString());
}
return result;
}
}
}
Try something like this
success: function(data) {
response($jQuery.map(data, function(item) {
return {
label: '' + item + ''),
value: item
}
}))
}