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.
Related
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>
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");
I can make variables one by one like this:
var bookName = document.getElementById('bookName').value,
author = document.getElementById('author').value,
translator = document.getElementById('translator').value,
pageCount = document.getElementById('pageCount').value,
publisher = document.getElementById('publisher').value,
isbn = document.getElementById('isbn').value,
printingYear = document.getElementById('printingYear').value;
But it's so hard to write and it doesn't fit with the DRY rule. So I changed the code to this:
function variableMaker(argument) {
var tags = document.getElementsByTagName(argument);
for (var i = 0; i < tags.length; i++) {
var tags[i].name = tags[i].value;
}
}
variableMaker(input);
But I can't understand if it is the true way or if it is working? How do I check if it's true or not?
In this code, I tried to get the computer find all the input tags and make variables with their name property and assign it to its values for each of them.
If I understand correctly then you want to gather data from all <input> elements. If so, then you need to call it like this:
variableMaker('input'); // use quotes!
Still even then your function does not return anything, it just ends.
You'd also better create your own object for the return collection, instead of adding values to an existing object.
Here is a working solution:
function variableMaker(tagName) {
var elements = document.getElementsByTagName(tagName);
var items = {};
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
items[elem.id] = elem.value; // Use id as key, each points to the corresponding value.
}
return items;
}
var values = variableMaker('input');
console.log(values); // show the entire return object
console.log(values.author); // access individual items from the return object
console.log(values.isbn);
<input type="text" id="author" value="Dahl">
<input type="text" id="isbn" value="1234">
.
I've been searching for an answer of this concept for a whole day and finally gave up and decided to ask it here.
Here's the concept:
I have a set of fields which are arrayed, I want that set of fields to be inside of array so that I can use a standard function for saving a module based on the fields involved and another param to check which to save.
Sample code:
module1.php
<?php
$i=0;
while($i<5){
?>
<input type="text" name="field1[$i]" />
<input type="text" name="field2[$i]" />
<input type="text" name="field3[$i]" />
<?php
$i++;
}
?>
<input type="button" name="process"
onclick="checkFields(['field1', 'field2', 'field3'], 'module1');" />
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn); //Output is 3
for(i=0; i<fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn); //Output should be 5
}
}
</script>
So, that part with comment is the thing I can't figure how to do, I tried using getElementById, getElementsByName but it's not working.
Or is there any possibility that I can pass an array of elements like this: array(field1, field2, field3) to a function?
Edit: I added a while loop statement to make the concept more comprehensive.
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn);
for(i=0; i<=fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn);
}
}
</script>
You should be applying the indexer on the f parameter, instead of the fn variable which is an integer.
fn is the length of your array, not your array. You should be using f
Change...
var nfn = fn[i].length; //Here's where it's not working
To...
var nfn = f[i];
Also, you will find that the for loop will fail, as i will reach fn but the array stops at fn-1
So change...
for(i=0; i<=fn; i++){
To...
for(i=0; i<fn; i++){
f[i] still points to just the incorrect input names. You don't really get access to the input field.
Do this:
var inputName = f[i] + "[]";//remember the input name is field1[] and not field1.
var value = document.querySelector( "input[name='"+inputName+"']" ).value;
the value here is just the input text of the input field and not really an array. If you have multiple fields with the same name, then use document.querySelectorAll method to get all the input fields and then iterate to get the values one by one.
To help you understand better, consider these 2 options:
Option 1:
html:
<input name="field1[]" />
<input name="field1[]" />
access the value:
var inputFields = document.querySelectorAll("input[name='field1[]']");
var values = [];
for (var j = 0; j < inputFields.length; j++) {
var val = inputFields[i].value;
values.push(val);
}
Option 2:
html:
<input name="field1[0]" />
<input name="field1[1]" />
access the value:
var values = [];
var j = 0;
var inputField;
while (true) {
var inputField = document.querySelector("input[name='field1[" + j + "]']");
if (!inputField) break;
values.push(inputField.value);
j++;
}
Note that, in option 1, there are multiple fields with the same "name" and in option 2, there are multiple fields with unique names.
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));.