Jquery Autocomplete widget implementation - javascript

I am trying to convert a normal field to autocomplete and making a ajax call to get the data in JSON and then set it to that autocomplete.
I do not know much on JQUERY, I spent around 5-6 hours just to know I have to initialize before using any function on the auto complete field.
What I have done so far
I managed to initialize and convert my text field to autocomplete and checked that using the inspect option it shows autocomplete , and also am able to make the ajax call which is pulling the data verified that using f12 network option.But it does not show up as a type ahead in my autocomplete option.
HTML
<div id ="myName">
<table class="some_class">
<tbody>
<tr>
<td >
<label>NAMES</label>
</td>
</tr>
<tr>
<td >
<input type="text" id="nameText" />
</td>
</tr>
</tbody>
</table>
</div>
initialization part
myName.on('valueChange',function (value){
$("#nameText").autocomplete({
appendTo:"#nameText",
source:function(event,ui){
var name=myName.value();
$.ajax({
url: "www.getmeSomeData.com/query/name:"+name,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
}
});
},minLength:1});
});
$("#nameText").focus(function(even,ui){
$((this).data("uiAutocomplete").search$(this).val());
});
PROBLEM
1.The autocomplete does not show any result even though from ajax call i see json data coming.
2.The value change starts only after i type abc and then move the cursor somewhere else and then click it back,before that nothing invokes.Where as what is expected is as soon as I type a or ab or abc it should make ajax call and pull the data show in autocomplete dropdown.
Can someone please help? I did not come here without researched but I think i tried a lot of things and nothing worked so am totally confused.Kindly help me, i have spent around 2 days on this.
Thanks in advance.

I finally figured out what was the problem in my code.I actually was not able to add option to my input autocomplete.To make it work I needed to update my html with
HTML
just replace <input class="nameClass" type="text" id="nameText" />
And the jquery part needed updates, the above was just a very novice attempt.
1. I should have used $.each($(".nameClass"), function(index, item) {
2. and then $(item).autocomplete
3. Also in source should have used source:function(request,response)
4. In the ajax call request.term (which will take whatever you input in the autocomplete field where as my method was invoking the ajax call only after tab out.
5. Map the data of response response($.map(data.data, function(item){
6. Write a select callback function to make anything happen after i click on any entry in the typeahead
7.data("ui-autocomplete")._renderItem = function (ul, item) { >To show the data in a formatted way after the ajax call.
INITIALIZATION
$.each($(".nameClass"), function(index, item) {
$(item).autocomplete({
source:function(request,response){
$.ajax({
url: "www.getmeSomeData.com/query/name:"+request.term,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
response($.map(data.data, function(item){
return{
value:item.somethigncomingfromJson //will set into the field
data:item
}}))}}
});
} ,minLength :2,
select:function(event,ui){
//do something on select of a row in the autocomplete dropdown
}}).data("ui-autocomplete")._renderItem=function(ul,item){
return $("format in which you want to see the data").appendTo(ul);
});
}
No other event is required.

Related

Using JS or AJAX to live search filter through JSON object on page (laravel)

I'm new to AJAX and a lot of JS, but I need to replace some old angular functionality on our Laravel site.
We simply have a page with a static/sticky header search bar, but no submit button. It needs to do a live filter upon search input. i.e. if I type sofa, it should hide anything from the page without the word sofa.
The Laravel blade/HTML is built with foreach loops from controller data, but more importantly, the data is stored in a JSON object called orderFormData, shown below.
I need a simple and effective live search filter to hide anything that doesn't match between the JSON and the search bar. The page is built with multiple HTML tables so I don't want to filter by the table and I think that's too complicated and convoluted. It should suffice to do it by JSON, possibly with AJAX. However, I'm a total novice here and I'm desperate for a solution.
Here's the search html:
<div class="md-input-wrapper search-form">
<form class="uk-search" id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
</div>
Here's the JSON object and some JS that I was playing with, but it doesn't work:
<script type = "text/javascript">
var orderFormData = <?php echo json_encode ($tempdata);?>;
$(document).ready(function(){
$('#srch-term').on('keyup',function(){
var searchTerm = $(this).val().toLowerCase();
$('.uk-table tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
</script>
This is just a pure JS idea, but I'm interested in AJAX as well if it will work better for this scenario. How can I properly filter items on the page by tying the search bar and JSON object?
You don't need of Ajax to do a search function with hide and show, this is simply manipulating DOM, instead ajax can calls the json from the php and with jquery you can simple loop your td on keypress and use :contains of jquery, onkeypress you call a function and in this function you do show and hide if contains "search" show otherwise hide.
Here a simple example in one of my old project #tabellaWebLog was the id of the table ricercaUser was the id of the input search and trTabellaWebLog was the id of the row where i wanted the search instead .ricUser was the class of the table column to loop the search inside the table...Bye
user = $('#ricercaUser').val();
$('#tabellaWebLog').find("#TrTabellaWebLogRiga:not(:contains('"+ user +"'))").hide();
$(".ricUser:contains('" + user + "')").parent().show();
$(".ricUser:not(:contains('" + user + "'))").parent().hide();

How to get modified text from input JQuery or javascript

I'm having a problem getting modified text from input. The input is loaded with some text I get from a database and with an option i should take the onlyread attr off and change the values. Thats ok but when i click on the save button after writing something else in the inputs, it gets the old values with .val(). How can i get the new ones?
The code is something like this.
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
$.ajax({
type: "POST",
dataType: "html",
success: doSomething,
timeout: 4000,
error: someProblems,
url: "modules/mod.php",
data: {anInput: anInput, otherInput: otherInput}
});
I added the AJAX code just to mention that i need the values to do something. AJAX is working.
I know this can be done with a form but that will reload the page and I don't want that.
Sorry for my rusty English and thanks :)
EDIT: Perhaps I'm not correctly speaking when saying "change the values" what I'm doing is selecting the text and writing something else.
I show some information with the inputs, click a button that allows me to modify, type some new text in the inputs and then click "save"
HTML is genereted by another AJAX
<div class="infoVideo">
<input id="anInput" value="someTextFromDataBase">
<input id="otherInput" value="someTextFromDataBase">
<input type="button" id="btnMod">
<input type="button" id="btnSave">
</div>
If I erase and type something else in the input .val() is getting old someTextFromDataBase
Edit: As per a guess in my comments, there was more than one #anInput in the page so the code was only retrieving the value from the first one which was not the one being edited. The solution is to not have any duplicate id values in the HTML of the page.
I suspect that your code isn't really like you show. You are probably doing these:
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
only once and then trying to use anInput and otherInput much later when the form fields have already changed. You can get the current values by not caching those and just retrieving the current values when you need them by changing this:
data: {anInput: anInput, otherInput: otherInput}
to this:
data: {anInput: $("#anInput").val(), otherInput: $("#otherInput").val()}
That way, you are always retrieving the latest and greatest values right before your Ajax call.
Please confirm format of data returned by mod.php. The AJAX block is expecting to receive HTML formatted text dataType: 'html', -- but you are sending json, so is that what you are expecting back?
If this note doesn't reveal the solution, then please show us your doSomething function - that's where the returned data is handled.
Probably you've tried this already, but what happens if you do this:
var anInput = $("#anInput").val(); //gets old value
alert(anInput);
var otherInput = $("#otherInput").val(); //gets old value
alert(otherInput);
$.ajax({ //etc });

Specific pop up with ajax and query from database

I use in a form a simple radio button with "YES" or "No", I wish that when I click yes a pop-up window will be automatically shown with this specific message:
Are you sure you want to sell a new membership to [User’s Full Real Name from database] with the number [ number of product from database ] ?
That means at the same time an ajax query will be established to return the name of user and the number of product from database.
I'm not very good in JS/Ajax, can anyone help me with this?
Edit :
I know to do what you wrote in the message bellow,what I'm not sure is how to run the pop-up window automatically when I choose "yes" radio button?
To use ajax, you first need to create a server-side function that does what you need. For instance, a php script that takes a userID and returns the user's full name. Let's suppose you create that script and call it "username.php".
On your page, you'll use a javascript function, such as the jquery .ajax function to send an asynchronous request to username.php. The function call will look something like this:
function lookupUsername(){
$.ajax({
type: "POST",
url: "username.php",
data: { ID: $("#userID").val() }
}).done(function( msg ) {
alert( "Username: " + msg );
});
}
In the above example, I've assumed that the user ID is embedded somewhere on your page in an element with ID="userID". The term $("#userID").val() is a jQuery function that looks up the value of the HTML element called "userID".
Next, you need to call the lookup function when the yes radio button is clicked. So something like:
<input type="radio" name="foo" id="foo" value="yes" onclick="lookupUsername()" />
Note that to use the JQuery framework (The .ajax() function and the $() selector function, you need to include the JQuery framework on your page:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
It's totally possible to do an ajax call without jQuery, but the code is a little messier.

jQuery cleaning HTML table

This is my table:
<tr class=stuff>
<td id=id></td>
<td id=city_id></td>
<td id=temp></td>
<td id=date></td>
</tr>
This is my Javascript:
<script>
$(document).ready(function() { // waits when document is ready
$('.data').change(function() { // when dropbox value changes do this
getWeather(); // here I tried inserting table clearing code
});
});
function getWeather() {
$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) { // JSON request
$("#id").text(data.id); // changes fields accordingly
$("#city_id").text(data.city_id);
$("#temp").text(data.temperature);
$("#date").text(data.date);
});
}
</script>
Every item in dropdown menu does not have response from server, so I want it to clear the table just before making a new JSON request. So when JSON comes back with data, data is updated accordingly, but when JSON comes back with nothing, then all the tables will be empty.
At the moment when JSON retrieves no data, the old data still remains in the table.
I tried using $('.stuff').remove() and $('.stuff').clean() , but after using them right before getWeather(); then later I wasn't able to put info into table which I received from JSON. It just did not work anymore.
Feel free to ask any questions.
Try this
$('.stuff td').text("");
getWeather();
Depending how much of this sort of thing you will be doing on your site you might want to look into KnockoutJS, it is designed for dynamic displays with changing data, including auto hiding sections.

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources