Ignore case-sensitive input in an array? - javascript

I want to search a value in an array, but the search should ignore lower/upper-case letters.
How can I accomplish this?
This is my code:
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "json",
data: { pageType: pageType, input: request.term, dataString: 'getPageInfo' },
success: function(data)
{
var values = $.map(data, function(item) { return {id: item.id, label: item.label, value: item.value}; });
for (var i = 0; i < values.length; i++) {
if (values[i].label.split(',').indexOf(request.term) >= 0) {
var found = values[i];
}
}
if (!found) values.push({id: 0, label: request.term + ' hinzufügen', value: request.term});
response(values);
It's about giving the option to create a new entry, if the input already matches an entry to prevent creating duplicate entries by the user as you can see in the last line. request.term is the value entered by the user and values is the array.
So for example, if I'm searching for "berlin" or "BERLIN" or "bERLiN" and the entry in my database is "Berlin", then it should still mark this item as found in the array.

One option would be to force things upper- or lower-case beforehand:
var iterm = request.term.toLowerCase();
// ...
if (values[i].label.toLowerCase().split(',').indexOf(iterm) >= 0) {
Alternately you could turn request.term into a case-insensitive regular expression, but doing so involves escaping all of the characters in it that might be special in regular expressions, which is a pain. You'd have to be looking through a lot of values for the toLowerCase overhead to make me want to look at that complexity.

Convert the values and term to lowercase:
if (values[i].label.toLowerCase().split(',').indexOf(request.term.toLowerCase()) >= 0) {
var found = values[i];
}

Related

Use a unicode string in JSON file as function parameter

I'm using the answer from this question to create random characters:
String.fromCharCode(0x30A0 + Math.random() * (0x30FF - 0x30A0 + 1));
I created a function with the same principle so I can change the first and the last character of the range:
function uni_char(first, last) {
var char = String.fromCharCode(first + Math.random() * (last - first + 1))
return char;
}
For example, if I run the function with 0x0000 and 0x007F as parameters, it works as expected. What I'm trying to do is to read a JSON file with multiple character ranges to use them with the function. This is the JSON:
[
{
"first": "0x0000",
"last": "0x007F"
},
{
"first": "0x0080",
"last": "0x00FF"
}
]
I populate an array with the JSON file data using the answer from this question:
var blocks = [];
$.ajax({
async: false,
url: '/scripts/data/blocks.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
blocks.push(data[i]);
}
}
});
But when I use the values from the array with the function:
uni_char(blocks[0].first, blocks[0].last);
It just creates a � symbol. What am I missing? Maybe an encoding problem? Or a logic problem?

AJAX JSON response is returning the correct values, but also undefined values in between?

I'm working on some JavaScript code that is going to find the smallest unused number in a specified range of numbers. The AJAX request gathers all used numbers in the specified range, but is additionally returning undefined values in between the correct values? I've compared the returned values from the JSON response to what's currently in the SQL table and all the correct values are in both the JSON response and the SQL table, so I'm not sure where the undefined values are coming from.
https://imgur.com/a/rXLfEJk
JavaScript:
//Specified range of numbers to search.
var startRange = 40000;
var endRange = 49999;
//UPC's are padded with to 13 digits with 0's then sent as parameters.
var startUPC = '00000000' + startRange;
var endUPC = '00000000' + endRange;
// AJAX call to web API that gathers all UPC's within a range.
$.ajax({
url: "api/GetNewPLU",
type: "GET",
dataType: "json",
data: { 'startUPC': startUPC, 'endUPC': endUPC },
success: function (data) {
$.each(data.data, function (i, UPCs) {
for (var i in UPCs) {
console.log("UPC: " + UPCs[i].F01);
}
})
},
error: function (error) {
console.log(`Error ${error}`)
}
})
JSON Response:
{
"draw": null,
"data": [{
"DT_RowId": "row_0000000040002",
"OBJ_TAB": {
"F01": "0000000040002"
}
}, {
"DT_RowId": "row_0000000040008",
"OBJ_TAB": {
"F01": "0000000040008"
}
}, {
"DT_RowId": "row_0000000040013",
"OBJ_TAB": {
"F01": "0000000040013"
}
}, {
"DT_RowId": "row_0000000040017",
"OBJ_TAB": {
"F01": "0000000040017"
}
}
}
I plan to loop through the used numbers from the AJAX request comparing them to a sequentially incremented generated number until there is not a match and then save that unused number. I'm not sure if it's worth figuring out why I'm returning both values and undefined or if I should just find a way to filter out the undefined.
lodash _.difference can help to you.
Create two arrays. One for generated values, one for used values. And find diff between them.
var created = ["0000000040000", "0000000040001", "0000000040002"];
var used = ["0000000040001", "0000000040002"];
var unused = _.difference(created, used);

Javascript (Ajax) Parse JSON value

total javascript noob here. Just trying to get an understanding for the language.
I'm requesting a JSON request using the following code:
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
}});
The get request returns something like this:
"items": [
{
"topLevelComment": {
"authorDisplayName": "a"
"textDisplay": "b"
},
{
"topLevelComment": {
"authorDisplayName": "c"
"textDisplay": "d"
}
I would like to cycle through the AuthorDisplayName and textDisplay and randomly pick one from each. The best way to do this would probably be to put them both into arrays if I had to guess. I'm not sure how to even go about this.
var json={
"items": [{
"topLevelComment": {
"authorDisplayName": "a",
"textDisplay": "b"
}
}, {
"topLevelComment": {
"authorDisplayName": "c",
"textDisplay": "d"
}
}, {
"topLevelComment": {
"authorDisplayName": "e",
"textDisplay": "f"
}
}, {
"topLevelComment": {
"authorDisplayName": "g",
"textDisplay": "h"
}
}]
};
$("input:button").on("click",function(){
selectRand = Math.floor((Math.random() * json.items.length))
var r=json.items[selectRand].topLevelComment.textDisplay;
console.log(r);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="selectRand"/>
If your data is already in Object format, and you only want to get one from random pick. Then you don't have to loop for all the data. Just randomly select one index from your total data.
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
var randomIndex = Math.floor((Math.random() * data.items.length));
console.log("Selected data authorDisplayName: " + data.items[randomIndex].topLevelComment.authorDisplayName);
console.log("Selected data textDisplay: " + data.items[randomIndex].topLevelComment.textDisplay);
}
});
}
items is already an array. So you do the following:
Parse the result to json (Only if a string is returned)
items = JSON.parse(items)
Get a random index
let index = Math.floor((Math.random() * items.length))
Get the random data
let authorDisplayName = items[index].topLevelComment.authorDisplayName
let textDisplay = items[index].topLevelComment.textDisplay
As far as i understood you are trying to display a random object from the items array?
The items variable is already an array, so you don't need to create one. To get a random element of the array you can use the following code:
var item = result.items[Math.floor(Math.random()*items.length)];
I'm not sure where exactly the items array is located, let's say it's on the root of the result. You will probably also need to run the array through the method JSON.parse() to make it a valid JavaScript object.
And then to get the text and display name you can do this:
var authour = item.topLevelComment.authorDisplayName;
var text = item.topLevelComment.textDisplay;

Assigning attributes from an array

I am trying to build a form based off of column names I get from a PHP script, through AJAX, and a pre-defined array of column details. I am hoping to assign these pre-defined attributes to the incoming columns and build a form. For example, if I ever get the column "UserName" I want to to always be an < input >
The template
var template = {
UserName : {
label: "User Name:",
type: "input"
}
UserId : {
label: "User Id:",
type: "text"
}
}
Incoming JSON array from AJAX request
{"UserName":"bob", "UserId":"1"}
Now I need to somehow 'match' these. I myself am not sure exactly what to do here.
$.each(data, function(i,e){
// if index (such as UserName) is found in template array, maybe add the attributes to it?
});
For your case, use obj.hasOwnProperty(key) to test if it exists, concatenate a string and use a ternary assignment to build a input element. You could also use an if statement if you wished.
var $html = '';
$.each(data, function(idx,v){
$html += template.hasOwnProperty(idx)? '<input type="'+template[idx]['type']+'" name="'+idx+'"/>': '';
});
console.log($html);
Here's your jsFiddle
An alternative (and perhaps wordier) solution including label processing might be shown in this jsFiddle. The high level is based on the following code:
$(function () {
var template = {
UserName: {
label: "User Name:",
type: "input"
},
UserId: {
label: "User Id:",
type: "text"
}
};
var data = {
"UserName": "bob",
"UserId": "1"
};
$.each(data, function (key, value) {
if (template[key] != undefined) {
$("#here").append($("<span>" + template[key].label + "</span>"));
$("#here").append($("<input type=\"" + template[key].type + "\">"));
$("#here").append($("<br>"));
}
});
});

Jquery: Autocomplete with label

I am trying to learn website development.
While learning autocomplete feature of jquery, I tried to put in the labels.
function autocomplete (data) {
var data = data.toString();
var availableTags = data.split(',');
var autocompleteData = [];
for (var i = 0; i < availableTags.length; i++){
autocompleteData[i] = {};
autocompleteData[i].label = i.toString();
autocompleteData[i].value = availableTags[i];
}
$("#tags").autocomplete({
source: autocompleteData,
select: function (event, ui) {
printautocomplete(event, ui)
}
});
};
The autocomplete[i].value is a valid string.
autocompleteData[0]
Object {label: 0, value: "Peter"}
However, I do not see any suggestions.
What is wrong with the way I am using the API?
The API says:
"Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
OR An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label. "
Thank you.
$('#sidebarSearch').autocomplete(
{
source: function(query, result)
{
var query = $('#sidebarSearch').val ();
$.ajax(
{
url:"sidebarSearchFetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item)
{
return {
label: item.name,
value: item.usrId
};
}));
}
})
},
appendTo: "#sidebar-form"
});
I am skeptical of line 2 in your code (var data = String()data;) I would use: var data = data.toString();
But if you are sure that the autocompleteData elements do indeed have valid strings, then my best guess would be that perhaps you forgot to give the '#tags' id to your html entry field element.
Finally, if this is not it, to troubleshoot, I would try removing the select: option from the object you are passing to autocomplete() in the line that begins: $("#tags").autocomplete(... so that only the source options is passed.
Another thing to check out is when the code is being run. It is possible that a document.ready() function is needed to ensure that that when the autocomplete feature is added to the DOM element with the id '#tags', that the element has already been created.
The autocomplete works fine. Instead of completing "value", it completes "label".
So when I type in "1", it suggests "1", "10", "11", etc.
Autocomplete applying value not label to textbox answers how to change to to by-value.

Categories

Resources