Reading Javascript local storage to populate autocomplete - javascript

I need to autocomplete a text field in a form. The data for the autocomplete will change from time to time, so I want to autopopulate the autocomplete. This will be running standalone with no net access, so I need a client side solution. Having the user select a file for the autopopulate is out of the question, so I wrote a .js file that creates a JSON object with the data to populate the autocomplete, as well as other data associated with the selection for the field.
I know the auto complete works if I give it a simple array:
$(function() {
var cityList= ["Arlington Heights","Winnipeg","Miami Gardens","Louisville","Del Mar","Wilmington","Berkeley","Vancouver",]
// var cityList= "Arlington Heights,Winnipeg,Miami Gardens,Louisville,Del Mar,Wilmington,Berkeley,Vancouver,"
$( "#autocomp" ).autocomplete({ source: cityList });
});
However, when I read in the data from the .js file, things get really weird. This is the code I am using:
$(function() {
citiesData ();
var city = JSON.parse(localStorage.getItem( ['cityData']));
var cityList = '[';
for(var row in city) {
cityList = cityList += '"' + city[row].city +'",';
};
cityList += ']';
// document.write('<br />' + cityList);
$( "#autocomp" ).autocomplete({ source: cityList });
// document.write('<br />; checkpoint 1');
})
By uncommenting the document.write above the autocomplete line, I can see that the variable cityList is exactly the same as the array entered in the first example. By uncommenting both document.write lines, I can see that they each get written, so the code is not hanging on the autocomplete. However, if I uncomment either or both of the document.write lines, the form never appears on the screen. I believe I mentioned that it got weird.
My real problem is not with that weirdness. My real problem is that the autocomplete never populates, although my solution is very similar to the one at tutorialspoint.com/jqueryui/jqueryui_autocomplete.htm. I would really appreciate any insights into what my problem is with this.
I would also be interested if anyone can explain the weirdness about the document.write lines.
I have posted both versions. The first is at http://mccalip.com/problem/index.html.
The problem version is at http://mccalip.com/problem/problem.html.

Here is the code that works:
$(function() {
readCity();
var cityList = new Array;
for (var c in arrayCity) {
cityList.push(arrayCity[c][0]);
};
$( "#autocomp" ).autocomplete({ source: cityList });
});
readCity() is a function that creates the 2D array, arrayCity. Each row in the array has the city name followed by other data.
I just need the city names in the array for the autocomplete function, so I loop through arrayCity and push the names into the 1D array, cityList.

Related

How to read ALT Codes using jQuery autocomplete

I'm working in a project and I'm facing a problem. I have some client stored in database, lets say one of them is Novák. Now I'm using jQuery (autocomplete), in order to get the clients in the client text field when I want to search. The problem is that, I'm geting Nov& #225;k instead of Novák. I have searched for an answer but could not find the correct one.
<script>
var availableWorkers = new Array();
#foreach(var w in selWorkers) {
var worker = w.fullName;
#:availableWorkers.push(#worker);
}
$(".workerTag").autocomplete({
source: availableWorkers
});
</script>
So, I think I have to add something here:
#:availableWorkers.push(#worker);
Thank you. All the best.

Modification JSON with input html in js

I'm learning JS and i'm trying to make a little app with node.js with JSON on.
I managed to get what I wanted in my json and put it in my html as input, with the json data as "value". When I click on the elements, we can change each of them, since they are inputs, and so I change their "value". Until then, everything works, but when I modify my 1st element of the list, all the elements are modified in the json...
And only the first element in my HTML changes my json, the others don't, they change but don't register in the json, and I have trouble understanding why.. I tried forEach and this.el but nothing works, it doesn't understand my data..
There is the code
var newValue = $("#snippetTitle").on("change paste keyup", function () {
    if (newValue.val() != $("#snippetTitle:input")) {
        for (var i = 0; i < jsonParse.snippets.length; i++) {
            newValueTitle = jsonParse.snippets[i].title = newValue.val();
            writeValue = JSON.stringify(jsonParse, newValueTitle);
            fs.writeFileSync('save/snippets.json', writeValue, 'utf8');
        }
    } else {
    }
});
Thank you for explaining to me how I could do so that each element could be modifiable, and especially that it is recorded in the json...
I'm not looking for complete solutions, just help to understand what to do.

Django: populate the field based on previous field value - missing the last step to make it work

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.
Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),
merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800,
initial='0.00',decimal_places = 2, max_digits=10)
Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:
def check_item_price(request):
if request.method == "GET":
item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
price = Merchandise.objects.get(id = item)
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?
and the url
url(r'^_item_price', views.check_item_price, name='_item_price' )
Calling the url manually works great, it returns the price in json format
And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.
<script type="text/javascript">
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
$('#price').append("<option value=" + data.value + "></option>");
});
});
});
</script>
Any pointers on what to fix in the javascript?
Thanks!
After letting it marinate in my head for 2 months, I went back to it and finally made it work. Here is the right code
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
document.getElementById('id_merch_price').value=data;
});
});
});
</script>
First, the ID wasn't precise enough, but also the way of updating it wasn't the right one it seems. I truly feel lost anytime I have to do research on javascript or jquery. So may ways to do the same thing, it's almost impossible to learn for a casual coder like me.

Simple auto-completion function in javascript

I am trying to get a simple auto-complete function to work based off the usernames that a 3rd party app provides.
The app outputs data in this general format:
"{
"UserA":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserA"},
"UserB":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserB"},
"UserC":{"IP":"XXX.XXX.XXX.XXX","ConnectTime":"/Date(1435769694510)/","LastAskSource":"","LastAskType":2,"Name":"UserC"}
}"
Now, I want to use the general auto-complete function listed below:
$("#chatEntryBox").autocomplete({
source: usersOnline.Name
});
I have defined the array as such:
OnlineUsers = data.userinfo;
for (var i in OnlineUsers) {
var user = OnlineUsers[i];
usersOnline = $.map(OnlineUsers, function(el) { return el; })
}
Now, this part above works the way I would expect. I can test in the console what the values are of the array by doing JSON.stringify(usersOnline[0].Name);
I have looked at the documentation on the website for Jquery... I just think I am missing something or misunderstanding. If someone could point me in the right direction that would be great.
The end goal would be typing the first few letters of the users name, and it auto-completing the rest.
I made a fiddle for your problem here.
Loop to take out names from json can be as simple as this
var usersOnline = $.map(input, function(el) { return el.Name; })
$( "#chatEntryBox" ).autocomplete({
source: usersOnline
});

Using jQuery to pull text from a specific <td>

I'm running an AJAX query on an external page, and am attempting to only return the data from the County . My current script is pulling the text from all of the table cells, but I cannot for the life of me get it to simply pull the county name.
The current script that is being run:
$( ".zipCode" ).each(function( intIndex ){
var zipCodeID = $(this).attr('id');
console.log('http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID);
$.ajax({
url: 'http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID,
type: 'GET',
success: function(res) {
var headline = $(res.responseText).find("p").text();
console.log(headline);
$('#'+zipCodeID).empty();
$('#'+zipCodeID).append(headline);
}
});
});
An example of the page that is being queried:
http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip=56159
This should work for all entered ZIPS. The page layout is the same, I just can't get the function to return only the county. Any help or advice would be awesome. Thanks!
With the complete lack of ids and classes on that page, you don't really have much to go on. If you have access to the source of that page, stick an id or class on the cell and make your life so much easier. If not, you'll have to use what you know about the structure of the pages to find the county. Something like this will work specifically on that one page you linked to. If other pages have slight variations this will fail:
var headline = $(res.responseText).find("table > tr:eq(2) > td:eq(3)").text();
This assumes that there is only ever one table on the page and that the county is always in the 3rd cell of the 2nd row.
You're basically screen scraping. I somehow think you'll have issues with this due to cross domain and other things, but that is ancillary to the question.
You need to walk through the resultant page. Assuming there is only ever one page on the screen, it'll look like something this:
var retVal = [];
// Basically, for each row in the table...
$('tr').each(function(){
var pTR = $(this);
// Skip the header row.
if (pTR.find('th').length == 0)
{
// This is the array of TDs in the given row.
var pCells = $('td', pTR);
retVal.push({state:$(pCells[0]).text(), place:$(pCells[1]).text(), county:$(pCells[2]).text()});
}
});
// retVal now contains an array of objects, including county.
if (retVal.length > 0)
{
alert(retVal[0].county);
}
else
{
alert('Cannot parse output page');
}
The parsing code is written to be extensible, hence you get back all of the data. With postal codes, although you will likely only ever get back one county, you'll definitely get back more places. Also note... not every zip code has a county attached for a variety of reasons, but you should get back an empty string in that case.

Categories

Resources