Create/ creating the variable's dict dynamically and print - javascript

I want print the dict a in alert , (it is possible?) or print in the third's textarea (three) with id=p.
I read on this question and I used
document.getElementById("p").value=JSON.stringify(a);;
alert("myObject is " + a.toSource());
console.log(a);
These not function.
The example is :
<!DOCTYPE HTML>
<html>
<head>
<title>Example - print the dict</title>
</head>
<body>
<input id = 'button1' type = 'button' value = 'print the dict' onclick="updateHistory()"/>
<script type = 'text/javascript'>
var count ="?foo=1&oo=298529982";
function updateHistory()
{
var a = new Array();
for (var i = 0; i < document.formparam.elements.length; i++)
{
var field = document.formparam.elements[i];
a[field.name] = field.value;
}
document.getElementById("p").value=JSON.stringify(a);;
alert("myObject is " + a.toSource());
console.log(a);
}
</script>
<form method="GET" name="formparam" id="formparam" ><table><tr><td><textarea name="name" >john</textarea></td><td><textarea name="surname">jackold</textarea></td></tr></table></form>
<textarea id="p"></textarea>
</body>
</html>

Using JSON.stringify() on an array will iterate over the array like so:
for (var i = 0; i < a.length; ++i) {
// process value of a[i]
}
But because you're adding properties to the object using a[field.name], those are not added to the list of array items, unlike a.push(value). As such, JSON.stringify() will print [].
You should either:
Define a as an object, i.e. var a = {};
Iterate over the keys yourself:
for (var k in a) {
if (a.hasOwnProperty(k)) {
// process value of a[k]
}
}

var a = new Array();
should be
var a = {}; or var a = new Object();
There are no dictonnaries in JavaScript, however, you can use an object as a key/value store. To alert the object as JSON, you can just do alert(JSON.stringify(a));.

Related

How to match exact numerical pattern using FlexSearch

Is there a way to have FlexSearch (https://github.com/nextapps-de/flexsearch) find only results that contains exact character sequence including numerical characters ?
The documentation is there : https://flexsearch.net/docs/flexsearch-manual.pdf
There is a section page 35 called Analyzer that seems to give hints on how to do, but there is a TODO note at the end when is expected the list of Analyzer that we could try alternatively.
The following thread works fine only for plain characters : https://stackoverflow.com/a/69677055/2143734
Or if you know any equivalent efficient and browser compatible search API, it is just that I seem to miss something there !
If you input C3, 1, C0 or 4, you get results although none of these numbers appears...
var data = Array.from(Array(1000000).keys()).map(String);
data.unshift("CA", "VIS-CD", "CATDIR-U", "UE5", "GAE");
(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>
find only results that contains exact character sequence
ok, so instead of Array.prototype.includes logic, I used a cache system for the kind of search you want :D
var data = Array.from(Array(1000000).keys()).map(String);
data.unshift("CA", "VIS-CD", "CATDIR-U", "UE5", "GAE");
//in essence, you can just change the condition(match_condition) to append a result based on whatever other condition you want
//the edit has me changing the match condition :D
//the edit also has me attempting a cache block(for speed)
(function() {
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
var cacheText={}, resultLimit=100, length=Symbol(null) //I'm doing caching based on how you want results(as in your snippet this part will lag a bit)
for(let i=0;i<data.length;i++){
if(typeof data[i]!="string"){continue}
for(let j=0;j<data[i].length;j++){
let string="" //for caching all direct text indexes
for(let k=0;k<=j;k++){string+=data[i][k]}
if(!cacheText[string]){
cacheText[string]={[data[i]]:true}
cacheText[string][length]=1 //length measurement
}
else{
if(cacheText[string][length]==resultLimit){continue}
cacheText[string][data[i]]=true
cacheText[string][length]++ //adding to length
}
}
}
userinput.addEventListener("input", show_results, true);
function show_results() {
var {value}=this, values={}
let match_condition=(text)=> cacheText[value]?cacheText[value][text]:false && value!="" //match condition(that you can change to whatever other logic)
for(let i=0; i<suggestions.children.length; i++){
//the purpose of this loop is to only remove elements that won't be on the new result list
let matchCondition=()=>
!suggestions.children[i]? true: //test(if child still exists)
match_condition(suggestions.children[i].innerText) //condition(in this case if data exactly includes user input)
while(!matchCondition()){ suggestions.children[i].remove() } //remove only those which won't match up to the condition
if(!suggestions.children[i]){break} //end loop(since if this is true, there is no child left)
values[suggestions.children[i].innerText]=true //to indicate that this value already exists when doing the second loop below
}
for(let i=0; i<data.length; i++){
//the purpose of this loop is to append UNIQUE results
if(match_condition(data[i]) && !values[data[i]]){
var child=document.createElement('div')
child.innerText=data[i]
suggestions.appendChild(child)
}
}
}
}());
<body>
<input type="text" id="userinput" placeholder="Search by keyword..." />
<br></br>
<div id="suggestions"></div>
</body>

Save multiple inputs to localStorage

I'm trying to save multiple inputs to localStorage. I used a 'for' loop for this purpose, but it saved the same value for all three inputs. I want the separate foreach values, not all of them at once:
<script>
document.addEventListener('DOMContentLoaded', function() {
var j = document.getElementsByName('emploi').length;
var i;
for(i=0; i<=j; i++) {
var x = document.getElementsByName('emploi')[i];
x.value = localStorage['emploi'];
x.onchange = function() {
localStorage['emploi'] = this.value;
}
}
});
</script>
<!--Html-->
<!--SALE-->
<input type="text" name='emploi' placeholder='Sale'>
<!--les prof-->
<input type="text" name='emploi' placeholder='Professeur'>
<!--les classes-->
<input type="text" name='emploi' placeholder='Class'>
Store a JSON.stringified object instead of a simple string value otherwise you are using the same value for all 3
document.addEventListener('DOMContentLoaded', function() {
// parse stored JSON if it exists otherwise an empty object
var values = JSON.parse(localStorage.getItem('emploi') || '{}');
var inputs = document.getElementsByName('emploi');
for (let i = 0; i < inputs.length; i++) {
var x = inputs[i];
x.value = values[i] || '';// stored value if it exists or empty string
x.onchange = function() {
// assign value to the object above
values[i] = this.value;
// store updated version of object
localStorage.setItem('emploi', JSON.stringify(values));
}
}
});
It seems that your main issue is knowing how to save data to localStorage. You need to rewrite your code based on the syntax below.
Syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");
Syntax for READING data from localStorage:
const lastname = localStorage.getItem("key");
Syntax for REMOVING data from localStorage:
localStorage.removeItem("key");

How to get url data in html textbox

i have a simple code of javascript which displays text from url.
example: index.html?id=001
then its output displays in html page as 001. but i want that data (id=001) into html text box which display only "001" into textbox.
here is my code.
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
</script>
<br />
<script type="text/javascript"> document.write(GET("id")[0]); </script>
<br /><br />
<input type="text" id="" value="" name="" />
Actually i want that "001" into textbox as a textbox value.
Put the script after the input then just set its value:
<input type="text" id="myInput" value="" name="" />
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("(/\?id=)([^\&]*)"))[2]);
return data;
}
document.getElementById('myInput').value = (GET("id")[0]);
</script>
Regular expressions are probably overkill for this, and your expression will only find the querystring value if it immediately follows the ?.
You should use location.search rather than the full URL, because then you just need to take everything after the first character (which will be ? if there is anything), and it will eliminate hashes.
I used simple string splitting to create a reusable map of key/value pairs for lookup.
function GET() {
var data = [];
for (var i = 0; i < arguments.length; i++) {
data.push(getQueryMap()[arguments[i]]);
}
return data;
}
var queryMap = null;
function getQueryMap() {
if (queryMap) { return queryMap; }
queryMap = {};
var querySplit = location.search.substring(1).split('&');
for (var i = 0; i < querySplit.length; i++) {
var thisQuery = querySplit[i].split('=', 2);
queryMap[thisQuery[0]] = thisQuery[1];
}
return queryMap;
}
To use the input and get the value into it, you need an ID on it or another way to identify it:
<input type="text" id="someInput" value="" name="" />
Then, after it, put a script like so:
<script type="text/javascript">
document.getElementById('someInput').value = GET('id')[0];
</script>
Replace...
<script type="text/javascript"> document.write(GET("id")[0]); </script>
with...
<script type="text/javascript">$('input').val(GET("id")[0]);</script>
Place that line after the input box.
Here are a couple of functions that help you parse a URL's parameters into an associative array.
function transformToAssocArray(prmstr) {
var arr = {};
var prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
arr[tmparr[0]] = tmparr[1];
}
return arr;
}
function getURLParmeters() {
var prmstr = window.location.search.substr(1);
if (prmstr === null || prmstr === '' ) {
return null;
}
return transformToAssocArray(prmstr);
}
Then you can assign all URL parameters to a variable like this:
var params = getURLParameters();
From then on, you can access the parameter's value by referencing params.paramternamehere. So, to assign the value of the "id" parameter to a text input, just grab that input element and assign params.id to that input's value.
var inputElement = document.getElementById("myTextInput");
if (params !== null) {
inputElement.value = params.id;
}
This technique utilizes the HTMLHyperlinkElementUtils.search property to reliably separate URL location components from paramters, and then does a simple string split to separate key-value pairs and then store those pairs in an associative array.

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

Splitting data in my text field

Hello i am quite new to javascipt so please explain things clearly. I am currently running a php page which includes:
<input type="text" id="data"/>
<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>
this items array contains objects which is saved like this:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.ge27548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]tElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
the result of the page appears like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there anyway i can split the data so I can manipulate it one at a time like a loop or something. For example:
1st time:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
Next:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
etc.
Thanks.
You should JSON.parse() it like the save() method does when filling the oldItems array, then you can cycle the resulting array.
Example code:
<input type="text" id="data"/>
<script>
var myArray = JSON.parse(localStorage.getItem('itemsArray')) || [];
for (var i = 0; i < myArray.length; i++) {
var element = myArray[i];
// Do something with element.
}
</script>
The data is already returned in an array, which you can loop through with a standard for loop. However, you'll want to parse it first so that you then have an object that you can access using standard object methods.
For example:
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
var item = allItems[i];
console.log('Current item: %o', item);
// do whatever you want to it, etc.
}
Hi It looks like your save script is getting data from textfields and adding them as objects within an array.
the array is stored in your local storage and you can get it like this:
var items = JSON.parse(localStorage.getItem('itemsArray')) || [];
As this is an array you should be able to loop through it with a simple for loop:
for(var i in items){
// this has the i object within the array
var item = items[i];
// if you dont know the names of the keys in the array
// you can loop through this again using another loop
for(var j in item){
// you can then change this key like so:
items[i][j] = item[j].toUpperCase(); // (this makes the value upper-case for example)
}
// if you do know the names then you can just change them directly
items[i].q1 = items[i].q1.toUpperCase();
}

Categories

Resources