Is there a way to have FlexSearch (https://github.com/nextapps-de/flexsearch) find only results that contains exact character sequence ? I tried to put resolution to 25 and threshold at 22 as suggested, play around with Depth also, but I keep getting words that are close (sometimes a bit far, but at least the length is matching) but not always exactly matching my sequence.
my indexed words are sometime 3 letters acronyms, so maybe it messes up the contextual search.
If you play with the following code snippet, by entering CTD you get CTD (ok) and CDT (not ok.) If you enter CAA, you get CAA (ok) and Candidate (not ok)
var data =["CTD","CDT", "Candidate","CRT","CAA"];
(function(){
const index = new FlexSearch.Index({
charset: "latin:advanced",
tokenize: "full",
resolution : 25,
threshold : 22,
cache: true
});
for(var i = 0; i < data.length; i++){
index.add(i, data[i]);
}
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
userinput.addEventListener("input", show_results, true);
function show_results(){
var value = this.value;
var results = index.search(value);
var entry, childs = suggestions.childNodes;
var i = 0, len = results.length;
for(; i < len; i++){
entry = childs[i];
if(!entry){
entry = document.createElement("div");
suggestions.appendChild(entry);
}
entry.textContent = data[results[i]];
}
while(childs.length > len){
suggestions.removeChild(childs[i])
}
}
}());
<!doctype html>
<html>
<head>
<title>FlexSearch Sample</title>
<script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch#master/dist/flexsearch.compact.js"></script>
</head>
<body>
<input type="text" id="userinput" placeholder="Search by keyword...">
<br></br>
<div id="suggestions"></div>
</body>
</html>
I am probably missing something there but I believe there is a way to have the library generate a dumber index and exact matches rather than such a smart one with close matches.
Does this match your requirements?
P.S.
To avoid wasting time searching for diffs: I changed only the FlexSearch.Index call options.
var data = ["CTD", "CDT", "Candidate", "CRT", "CAA"];
(function() {
const index = new FlexSearch.Index({
charset: "latin",
tokenize: "full",
matcher: "simple",
cache: true
});
for (var i = 0; i < data.length; i++) {
index.add(i, data[i]);
}
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
userinput.addEventListener("input", show_results, true);
function show_results() {
var value = this.value;
var results = index.search(value);
var entry, childs = suggestions.childNodes;
var i = 0,
len = results.length;
for (; i < len; i++) {
entry = childs[i];
if (!entry) {
entry = document.createElement("div");
suggestions.appendChild(entry);
}
entry.textContent = data[results[i]];
}
while (childs.length > len) {
suggestions.removeChild(childs[i])
}
}
}());
<!doctype html>
<html>
<head>
<title>FlexSearch Sample</title>
<script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch#master/dist/flexsearch.compact.js"></script>
</head>
<body>
<input type="text" id="userinput" placeholder="Search by keyword...">
<br></br>
<div id="suggestions"></div>
</body>
</html>
Just to add some more thoughts to Daniele Ricci's answer : sometimes the "simple" matcher still picks up false positives (if we are looking for strict pattern) if request contains numbers. Again, my approach is probably too empirical to get a completely correct behavior, but here is an example that produces false positives. Changing tokenize to strict improves the situation but then you lose the matching for partial words. default matcher seems to be the one with less false positive... still some remain... :(
If you input C3, or C0 or 4, you get them...
var data = ["CA", "VIS-CD", "CATDIR-U"];
(function() {
const index = new FlexSearch.Index({
tokenize: "full",
matcher: "default",
cache: true
});
for (var i = 0; i < data.length; i++) {
index.add(i, data[i]);
}
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
userinput.addEventListener("input", show_results, true);
function show_results() {
var value = this.value;
var results = index.search(value);
var entry, childs = suggestions.childNodes;
var i = 0,
len = results.length;
for (; i < len; i++) {
entry = childs[i];
if (!entry) {
entry = document.createElement("div");
suggestions.appendChild(entry);
}
entry.textContent = data[results[i]];
}
while (childs.length > len) {
suggestions.removeChild(childs[i])
}
}
}());
<!doctype html>
<html>
<head>
<title>FlexSearch Sample</title>
<script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch#master/dist/flexsearch.compact.js"></script>
</head>
<body>
<input type="text" id="userinput" placeholder="Search by keyword...">
<br></br>
<div id="suggestions"></div>
</body>
</html>
Related
I am trying to write an html with JS program that will convert an excel file into json which is does bit it does not format it the way I need to. So basically it spits out when finished
[
{
"imei": "357271093291264"
},
{
"imei": "353094106032150"
},
{
"imei": "353112106434588"
}
]
but what I need is.
[
{
"imei": "357271093291264", "353094106032150", "353112106434588"
}
]
So it is taking imei from cell A1 and using it over and over. I just need it
to keep adding on as I go down the rows.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/read-excel-file#4.x/bundle/read-excel-file.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 50;margin-top: 80px;padding: 30px;background-color: #dedede;">
<h2>Excel to JSON Converter</h2>
<input type="file" id="input" />
<br> <br>
<textarea name="json-data" id="json-data" rows="25" style="width: 100%;"></textarea>
<br><br>
<button id="dl-json">Download JSON File</button>
</div>
<script>
var input = document.getElementById('input');
input.addEventListener('change', function(){
readXlsxFile(input.files[0]).then(function(data){
var i = 0;
var headers = [];
var json_object = [];
data.map((row, index)=> {
if (i == 0){
headers = row;
}
if (i > 0){
var temp = {};
for (var x = 0; x < row.length; x++){
temp[headers[x]] = row[x];
}
json_object.push(temp);
}
i++;
});
document.getElementById('json-data').value = JSON.stringify(json_object, null, 2)
});
document.getElementById('dl-json').onclick = function() {
var json_str = document.getElementById('json-data').value;
downloadObjectAsJson(json_str, '');
}
function downloadObjectAsJson(str, filename){
var data_str = "data:text/json;charset=utf-8," + encodeURIComponent(str);
var anchor = document.createElement('a');
anchor.setAttribute("href", data_str);
anchor.setAttribute("download", filename + ".json");
}
});
</script>
</body>
</html>
I have tried playing around with it and pulling out certain parts and setting different variables to certain values.
The shape of your output doesn't seem to make sense. Do you want the first element in your output array to be a key:value pair such as "headerText":"row2Value", and then the rest just strings?
If so, this should work for you:
var input = document.getElementById("input");
input.addEventListener("change", function () {
readXlsxFile(input.files[0]).then(function (data) {
let exportData = [];
for (i = 1; i < data.length; i++) {
i === 1
? exportData.push({ imei: data[i].toString() })
: exportData.push(data[i].toString());
}
document.getElementById("json-data").value = JSON.stringify(exportData);
});
document.getElementById("dl-json").onclick = function () {
var json_str = document.getElementById("json-data").value;
downloadObjectAsJson(json_str, "");
};
function downloadObjectAsJson(str, filename) {
var data_str =
"data:text/json;charset=utf-8," + encodeURIComponent(str);
var anchor = document.createElement("a");
anchor.setAttribute("href", data_str);
anchor.setAttribute("download", filename + ".json");
}
});
If you only need the key, then an array of values, this will work better for you:
readXlsxFile(input.files[0]).then(function (data) {
let exportData = [];
for (i = 1; i < data.length; i++) {
exportData.push(data[i].toString());
}
document.getElementById("json-data").value = JSON.stringify({
imei: exportData,
});
});
I'm developing a js, html & firebase webapp.
I'm trying to get list of scores from firebase and show them on html.
I think my query is working, but I can't show the results on html.
I tried first a code which worked on a video but it did not work for me (https://www.youtube.com/watch?v=NcewaPfFR6Y)
(html)
<p>
<ol id ="scorelist">
</ol>
</p>
(js)
function gotData(data) {
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = createElement('li', score);
li.parent('scorelist');
}
}
I get error createElement is not defined. When I try document.createElement then li.parent('scorelist') does not work and I get error li.parent is not a function.
Then I tried something like this but it did not work out either.
var scorelist = document.querySelector('#scoreslist')
function gotData(data) {
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = document.createElement('li', score);
scorelist = li.textContent;
}
}
I've been really stuck with this one! I would be grateful for some help, thanks!
I added an example with comments that may explain to you what i did.
function gotData() {
// you had typo on the id, make sure you select the correct element.
const scorelist = document.querySelector("#scorelist");
var scores = { first: { score: 1 }, second: { score: 2 } };
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
// first, create the element
const newListItem = document.createElement("li", score);
// and then, set the score as textContent of the newListitem.
newListItem.textContent = score;
// finally you should add the newListItem to the list parent element.
scorelist.appendChild(newListItem);
}
}
If you find problems, there might be input errors, built-in function problems, library api problems, algorithm problems, logic problems, etc. Try to read documents and find solutions for each possible problem.
method 1 Not use JQuery:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
If correct, list values will show below:
<p>
<ol id ="scorelist">
</ol>
</p>
</div>
<script>
function gotData() {
var scorelist = document.querySelector("#scorelist");
var scores = { first: { score: 660 }, second: { score: 330 } };
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = document.createElement("li");
li.innerHTML = score;
scorelist.appendChild(li);
}
}
//call the function
gotData();
</script>
<br>
<br>
The rest of the body
</body>
</html>
method 2 JQuery:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div>
If correct, list values will show below:
<p>
<ol id ="scorelist">
</ol>
</p>
</div>
<script>
function gotData() {
var scorelist = $("#scorelist");
var scores = '{ "first": { "score": 660 }, "second": { "score": 330 } }';
var objkeys = $.parseJSON(scores);
$.each(objkeys, function( key, value ) {
$.each(value, function(key, value){
li = $("<li/>");
li.css("color", "blue").text(value).appendTo(scorelist);
});
});
}
//call the function
gotData();
</script>
<br>
<br>
The rest of the body
</body>
</html>
Docs: createElement 1 2,
querySelector,
Object.keys 1 2,
selector, append, parent.
Also search your errors in stackoverflow. say get error createElement is not defined. see articles like jquery-document-createelement-equivalent, creating-a-div-element-in-jquery. And test result in websites, like jsfiddle
I have a program that is supposed to take two numbers entered by the user and send them to a function. This function will be used to determine all the prime numbers between those two numbers. However, I just can't seem to figure out how to find all the primes. I created an array that should hold all numbers between the two user submitted ones. But I don't know how to iterate through it and place all the prime numbers found into a new array. I know it's basic stuff, but for some reason I just can't figure it out.
Here's the code for my function so far.
function displayPrimeNumbers(p1, p2) {
var numbers = [];
var primes = [];
for(i = p2; i == p1; i++){
numbers.push(i);
for(i = 0; i < numbers.length; ++i){
if () {
}
}
}
}
<html>
<head>
<script = "text/javascript>
function prime(num1,num2)
{
var s="";
var count=0;
for(i=parseInt(num1);i<num2;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
count ++ ;
}
}
if(count == 0)
{
s=s+"\n"+i;
}
count = 0;
}
document.getElementById('textarea1').value = s;
}
</script>
</head>
<body>
<input type = "text" id = "num1">
<input type = "text" id = "num2">
<input type = "button" value = "Click here" onclick = "prime(document.getElementById('num1').value,document.getElementById('num2').value)"><br>
<textarea id = "textarea1" rows="10" cols = "20">answer</textarea>
</body>
</html>
I need help with below code.
What I need to do is to pass the URL parameters to these two hidden fields.
http://www.yoursite.com/index.php?fieldOne=Work&fieldTwo=Play
It doesn't seem to be working. Also I cannot add id to the form field.
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
<script>
function FillForm() {
var FormName = "myformname";
var qLoc = location.href.indexOf('?');
if(qLoc < 0) { return; }
var q = location.href.substr(qLoc + 1);
var list = q.split('&');
for(var i = 0; i < list.length; i++) {
var kv = list[i].split('=');
if(! eval('document.'+FormName+'.'+kv[0])) { continue; }
kv[1] = unescape(kv[1]);
if(kv[1].indexOf('"') > -1) {
var re = /"/g;
kv[1] = kv[1].replace(re,'\\"');
}
eval('document.'+FormName+'.'+kv[0]+'.value="'+kv[1]+'"');
}
}
FillForm();
</script>`
NULL had it kind of there with the simplification (albiet there is a small error in your code regarding the iteration over the query). Here is NULL's simplification corrected, and also my guess as to why you're not getting the desired results:
<form name="myformname">
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
</form>
<script type="text/javascript">
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query[i].split("=");
//alert(split);
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
</script>
1) Make sure you're using a form tag with an id. I can't see your HTML.
2) Be sure that you are not seeing new data appear in the hidden <input>'s? I advise using a debugger and checking the live DOM tree as opposed to the source code. Some debuggers don't update the source in real-time.
EDIT:
Based on new information from the questioning party, here is another stab at a fix:
<script type="text/javascript">
$(document).ready(function(){
var formName = "dSOfferAllE10Test-1349977611926";
var query = location.href.split("?").pop().split("&");
var len = query.length;
var split, elem;
for (var i = 0; i < len; i++ ) {
split = query[i].split("=");
$('form[name="'+formName+'"]').find('input[name="'+split[0]+'"]').each(function(){
$(this).val(split[1].replace(/"/g, '\\"'));
});
}
});
</script>
This uses jQuery, so make sure that you attach a reference to jQuery in your <head> (or at least near the top of the <body> if you don't have access to the <head>. Best to grab the snippet from the Google-hosted version: https://developers.google.com/speed/libraries/devguide#jquery
You can simplify your code:
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query.split("=");
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.
There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns