trying to implement live search in a input box - html

i'm trying to implement live search in a textbox, the list of options coming from the server, if the item is not available it should add dynamically, like if i type "gre" and selects that, it should added to the list or it should show in the top of the lists
Codeply :
https://www.codeply.com/go/d6WaXok32m
as specified in the code, the element 'entranceExamSearch' input box contails list of items

This code will give you some idea.
HTML:
<input type="text" id="searchPro" />
Your all the dynamic result will be show inside the div
<div id="searchLog"></div>
JQuery:
$("#searchPro").autocomplete({
source: function(request,response) {
$.ajax({
url: "php.func.php",
type: "POST",
data: { term: request.term },
success: function (searchData) {
$('#searchLog').html(searchData);
}
})
}
});
PHP: php.func.php
$find = "SELECT *
FROM tbl_products
WHERE (`product_name` LIKE '%".$_REQUEST['term']."%')";
$resset = $conn->query($find);
while ($res = mysqli_fetch_object($resset)) {
$findRes[] = $res;
}
if (!empty($findRes)) {
foreach ($findRes as $ResultSet) {
echo "<tr><td>".$ResultSet->product_name."</td>";
}
}else{
echo "<p>No Result Found for keyword <b>".$_REQUEST['term']."</b>..<p><hr/>";
}
Here is the link: [JQuery Autocomplete][1]
This is for your basic reference code i have use in my project. you can modify as per your need. Hope this will help you.
For more https://jqueryui.com/autocomplete/

Related

Knockout JS Checkbox List not binding

I have an issue where my checkbox list is not binding when loading data from the server.
So I have a table where you select a client when I click the edit button a bootstrap modal window popup with all the information fields such as first name, last name etc.
Now a couple of these fields are checkbox lists. Everything is being populated with the correct data except these two fields. Below is the current code of one of the lists.
<div class="row">
<div class="col-25">
<label for="referralSource">Referral Source</label>
</div>
<div class="col-75">
<ul class="kolist" data-bind="foreach: $root.sources">
<li>
<input type="checkbox" data-bind="
checkedValue: id,
checked: $root.currentClient.ReferralSourceIDs
" />
<label style="margin: 0px; padding: 0px;" data-bind="
text: source,
attr: {for: source}
"></label>
</li>
</ul>
</div>
</div>
This code should bind the data from the currentClient which is in the viewmodel.
self.currentClient = ko.observable();
On the edit button being clicked the currentClient is filled with the correct data.
editClient = function (editingClient) {
self.currentClient(editingClient);
}
The data we receive from the database fills up the ReferralSource class.
function ReferralSource(id, source) {
this.id = ko.observable(id);
this.source = ko.observable(source);
return this;
}
clientsLoad = function () {
$.ajax({
contentType: 'application/json',
type: "GET",
url: baseUrl + 'api/Client/LoadAll',
dataType: 'json',
context: this,
success: function (data, textStatus, jqXHR) {
self.clients($.map(data, function (item) {
var referralSources = new Array();
for (var i = 0; i < item.ReferralSourceIDs.length; i++) {
referralSources.push(
new ReferralSource(
item.ReferralSourceIDs[i].ReferralSourceID,
item.ReferralSourceIDs[i].Source
)
);
}
return new Client(
item.FirstName,
item.LastName, /* etc */
referralSources
);
}));
}
});
}
So with all that being said the load data is working fine the edit on select is being populated with the correct data but the only issue is that the check boxes are not being selected on bind. Can anyone see something I am missing or am I doing something wrong. If you need more info please ask, I will be trying to get this to work in the meantime.
EDIT: So I found a way to get it working and it has to deal with this part of the code.
<input type="checkbox" data-bind="checkedValue: id, checked: $root.currentClient.ReferralSourceIDs" />
It does not like $root.currentClient.ReferralSourceIDs. I removed this out of the class and put it into the view model and it started to work. So it looks like this now $root.referralSources. I have no idea why but it works that way. So if anyone has any other solutions please let me know for now I will stick with this.

AngularJS directive - access element's dataset

Here is my simplified template:
<div>
<img ng-click="addSubPlots($event)"
data-status="add"
src="abc.svg" />
</div>
And here is a directive that loads that template:
a.directive("trendChartToolbar", function ($templateRequest, $compile) {
return {
link: function (scope, elem, attrs) {
$templateRequest('template.html').then(function (html) {
var template = angular.element(html);
$(elem).append(template);
template = $compile(template)(scope);
});
}
};
});
My expectation was that I would be able to access template's dataset and modify the 'status' key. But when I check it the dataset is empty. I know that Angular removes 'data-' but I also dont see any 'status' anywhere. Any idea how to make something like this working? The reason I am trying this is when I click on a button I need to get button's status. Here is code I am using in the controller:
$scope.addSubPlots = function(event){
console.log(event.target.dataset.status);
}
Please share some ideas.
Thanks

Show MongoDB info in HTML

I'm working on a website using a MEAN stack, and now I am trying to show some MongoDB data in my HTML pages by using Angular. But I don't seem to get it done.
This is the data in MongoDB I want to show in my HTML
{
"badkamer" : {
"block1" : {
"title" : "Badkamer",
"content" : "string"
}
}
}
This is the Angular function retrieving the data:
app.controller('cityCtrl', function($scope,$http){
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data;
console.log(d.data);
},function(err){
console.log(err);
});
};
});
This is where I want it to show in my HTML:
<div ng-controller="cityCtrl" ng-init="specials()" ng-bind="special">
<div class="title">{{special.badkamer.block1.title}}</div>
<p>{{special.badkamer.block1.content}}</p>
</div>
</div>
When i console.log(d.data), I get this:
[Object]
0: Object
badkamer: Object
block1: Object
content: "Text",
title: "Badkamer"
But when I try it like this, the bind option shows all the data at once in my HTML. How can I get it working by using the Angular {{}} tags?
From the console.log, you can see that its an array, so you will need to use index, like this,
<div ng-controller="cityCtrl" ng-init="specials()" ng-bind="special">
<div class="title">{{special[0].badkamer.block1.title}}</div>
<p>{{special[0].badkamer.block1.content}}</p>
</div>
</div>
or change the code in controller.,
$scope.special = d.data[0];

Typeahead 0.11.1 not adding results from JSON

I'm trying to get Typeahead to add autocompletions from my JSON source, but there are no results being added.
Some background info: I've got Sinatra serving a JSON page which takes a query param, here's the code:
get '/search' do
content_type :json
Movie.search(params[:q], {
fields: ["title^5"],
limit: 10,
load: false
}).map(&:title).to_json
end
and it's working; here's an example result.
/search?q=toy%20story returns:
["Toy Story"]
My HTML input looks like this:
<input id="search-box" type="text" value="" placeholder="Search for Movie Title" class="form-control" name="search">
and my JS:
$(function() {
$('#search-box').typeahead({
highlight: true,
limit: 10
},
{
display: 'movie',
source: function(query, syncResults, asyncResults) {
$.get('/search?q=' + encodeURIComponent(query), function(data) {
asyncResults(data);
console.log(data);
});
}
}
})
The results are showing up in the console.log as I type, and the Typeahead HTML entities are added, but with nothing in them and they're hidden.
Can anyone help? I've been stuck on this all day.
I strongly believe it is display: 'movie' that is causing your problems. If you return an array of strings, i.e ["Toy Story"] then you want to show the value of the array items :
display: 'value'
otherwise, if you work on an array of JSON items, like
[{ "title" : "2001: A Space Odyssey" } , { ... } ]
then display (or displayKey) should refer to the key / value pair you want to show in the dropdown :
display: 'title'

Prevent Ajax.BeginForm from HTML encoding output

#using (Ajax.BeginForm("Create", "Comment",
new AjaxOptions
{
UpdateTargetId = "newComment",
OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }",
}))
{
...
}
outputs the following markup:
<form action="/Comment/Create" data-ajax="true" data-ajax-mode="replace"
data-ajax-success="function() { alert('finished 34'); }"
data-ajax-update="#newComment34" id="form1" method="post">
As you can see, it has HTML encoded my javascript. How do I prevent this?
EDIT: I have multiple AJAX forms on my page so the onsuccess function needs to know which one called it. In my code, you can see I am trying to pass state to this function. If OnSuccess can only take a function name (and not state), then how can I achieve this?
Personally I would use a standard Html.BeginForm helper with HTML5 data-* attributes that I will AJAXify myself:
#using (Html.BeginForm(
"Create",
"Comment",
FormMethod.Post,
new { data_id = Model.Id }
))
{
...
}
which outputs:
<form action="/Comment/Create" data-id="some id here" method="post">
...
</form>
and then in a separate javascript file I would subscribe for the .submit event:
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataId: $(this).data('id'), // <- pass the data-id HTML5 attribute
success: handleSuccess
});
return false;
});
});
function handleSuccess(result) {
$('#newComment').html(result);
// fetch the data-id of the form that trigerred the AJAX request
var id = this.dataId;
// TODO: do something with this id
}
I prefer this technique compared to the Ajax.* helpers as it gives me all the control I might need. Another advantage is that we get a clear separation between script and markup making the code nice and tidy.
Don't.
The HTML encoding is correct behavior, and the attribute value (as seen from Javascript code) will not be encoded.
I believe that It's because MVC interprets the OnSuccess (and other vars) as the name of a Javascript function and not a bit of Script.
Make a helper function that performs the script you want to act on the submit.