Regarding autocomplete textbox - javascript

## 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();
}
}

Related

Bootstrap.css and Vendors.min.js are creating problem for an Autocomplete Textbox in Asp.net webforms

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;
}

MVC dropdown list with json data and chosen

I'm trying to populate dropdown list with jsonResult data on a second list
on change event. That works just fine. But I also want to use chosen on that list, and with that list is empty. It looks like chosen is not picking up list update. I'm pretty new in this so please help
First list:
<div class="col-md-10">
#Html.DropDownList("tipopreme_TipOpremeID", null, htmlAttributes: new { #class = "form-control", #onchange = "PopuniDropOpreme()" })
</div>
Second List:
#Html.DropDownListFor(x => x.ModelOpreme_ModelOpremeID, new SelectList(Enumerable.Empty<SelectListItem>()))
Controller:
public JsonResult getOpremaPoTipu(int? tipid)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (tipid != null)
{
foreach (var item in db.ModelOpremes.Where(x=>x.TipOpreme_TipOpremeID==tipid))
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString()});
}
}
else
{
foreach (var item in db.ModelOpremes)
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
Script:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen.jquery.min.js"></script>
<link href="~/Content/chosen.min.css" rel="stylesheet" />
<script type="text/javascript">
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
function PopuniDropOpreme() {
var tip = $("#tipopreme_TipOpremeID").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Opremas/getopremapoTipu?selectedValue=" + tip,
data: "{}",
dataType: "Json",
success: function (data) {
$('.ddlProjectvalue').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Value).html(item.Text));
});
$("ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
You got some errors in your code:
- url: "/Opremas/getopremapoTipu?selectedValue=" + tip, //wrong param name
- $('.ddlProjectvalue').find('option').remove(); //wrong id
They should be:
- url: "/Opremas/getopremapoTipu?tipid=" + tip
- $('#ModelOpreme_ModelOpremeID').find('option').remove();
You can follow my sample. Hope to help, my friend!
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
public JsonResult GetData(int? selectedValue)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (selectedValue != null)
{
foreach (var item in Data().Where(t=>t.Id == selectedValue))
{
lista.Add(new SelectListItem
{
Text = item.Id.ToString(),
Value = item.Value
});
}
}
else
{
foreach (var item in Data())
{
lista.Add(new SelectListItem { Text = item.Id.ToString(), Value = item.Value.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
private List<Test> Data()
{
var data = new List<Test>
{
new Test{Id = 1, Value = "A1"},
new Test{Id = 1, Value = "A2"},
new Test{Id = 1, Value = "A3"},
new Test{Id = 1, Value = "A4"},
new Test{Id = 2, Value = "B1"},
new Test{Id = 3, Value = "C1"},
new Test{Id = 4, Value = "D1"},
};
return data;
}
And code in View:
#{
ViewBag.Title = "About";
}
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css">
</head>
<body style="margin-top:50px;">
<script type="text/javascript">
$(function () {
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
$(".chzn-select").chosen().change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Home/GetData?selectedValue=" + id,
data: "{}",
dataType: "Json",
success: function (data) {
$('#ModelOpreme_ModelOpremeID').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Text).html(item.Value));
});
$("#ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
});
});
</script>
<select class="chzn-select" name="faculty" style="width:200px; margin:10%;">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<br />
<select id="ModelOpreme_ModelOpremeID" style="width:200px; ">
</select>
</body>
</html>

Error in Autcomplete TextBox

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();
});

Get words from database and pass them to a script file that runs in the browser

<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/

How to list autocomplete results as a link?

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
}
}))
}

Categories

Resources