i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);
Related
I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer
I am trying to make an small game as practice but I'm having a problem loading the name key from localStorage and putting it in tag.
<div id="profilescr" class="thetab">
<h3 id="tpname"></h3>
</div>
if(localStorage.user === undefined) {
localStorage.user = prompt("Name plz");
document.getElementById("tpname").innerHTML = localStorage.user;
}
I stored .user successfully but it is failing to show up in <h3> tag.
You're only updating the h3 when the value isn't stored. If the value is stored, you're not updating it, because you've put the update inside the if. Move it outside it:
if(localStorage.user === undefined) {
localStorage.user = prompt("Name plz");
}
document.getElementById("tpname").innerHTML = localStorage.user; // <====
Live Example on plnkr (since Stack Snippets don't allow local storage)
Instead of using localStorage.user, use the methods localStorage.setItem() and localStorage.getItem().
I'd change your code to the following:
if(localStorage.getItem("gameInfo") === null){
askForName();
}else{
const userName = JSON.parse(localStorage.getItem("gameInfo")).userName;
document.getElementById("tpname").innerHTML = userName;
}
And for the askForName function:
function askForName(){
const name = *some input value*;
localStorage.setItem("gameInfo", JSON.stringify({userName: name}))
}
I have a set of scripts that I'm using that interact with each other. I use a client, user event and suitelet script to create a button that, when pressed, opens a popup with a list of items filtered by vendor.
It works fine when I'm in edit however when I use it while creating a record problems arise. Since the record to be created has no vendor or id I can't retrieve an item by vendor. What I'm trying to do is to have the Suitelet retrieve the info from the vendor field that is entered prior to it being saved. Therefore I can filter all the items by vendor and add the necessary items in one go. Is this possible? Am I able to access the info before it is submitted.
Below are the Client and Suitelet. The User Event is just a call to the suitelet so for the sake of brevity I left it out.
Client Script
function addItemButtonCallback(data){
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', data);
nlapiCommitLineItem('inventoryitem');
}
function addItemButton() {
var id = nlapiGetFieldValue('id');
if (id != "") {
var url = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1') + '&poId='+id;
window.open(url, '_blank', 'width=500,height=500');
}
}
Suitelet
function suitelet(request, response){
if(request.getMethod() == 'GET') {
var form = nlapiCreateForm('Add Item');
form.addSubmitButton('Submit');
var itemfield = form.addField('custpage_val', 'select', 'Item');
var id = request.getParameter('id');
var rec = nlapiLoadRecord('purchaseorder', id);
var vend = rec.getFieldValue('entity');
var search = nlapiSearchRecord(...search parameters...);
for (result in search){
if (search[result].getValue('vendor') == vend){
itemfield.addSelectOption(search[result].id, nlapiLookupField('inventoryitem', search[result].id, 'itemid'));
}
}
response.writePage(form);
} else {
var data = request.getParameter('custpage_item');
response.write('<html><body><script>window.opener.addItemButtonCallback("'+data+'"); window.close();</script></body></html>');
}
}
Use nlapiGetFieldValue('entity') on the clientscript and pass it to the Suitelet using a query parameter just like you are doing with poId (if you do this you might not even need poId after all + no need to load the record on the suitelet).
Also, you might want to optimize your code by running one search passing an array of itemids instead of calling nlapiLookupField for each item.
You might need to modify your beforeLoad so the entity is inserted dynamically when the button is pressed (I cant remember if clientscript button does this) . Something like this:
var suiteletURL = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1');
var script = "var entity = nlapiGetFieldValue('entity'); var url = '" + suiteletURL + "'&entityId=' + entity;window.open(url, '_blank', 'width=500,height=500')";
var button = form.addButton('custpage_addItemButton', 'Add Item', script);
I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code¶meter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).
I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
var x;
//geting the username
x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = x.substring(x.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
//to get the username parameter from URL on new page
var z=window.location.search.substr(1);
//to get rid of some part of the username parameter
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
//to put the username to 'To' field
document.getElementById("search-q").value= a;
}
Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!
What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.
ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
var y;
//geting the username
y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>
<script>
//code running after page-load
window.onload = function() {
var z=window.location.search.substr(1);
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
document.getElementById("search-q").value= a;
}
</script>