Passing text from one page to the next using JavaScript - javascript

This is the job reference number I want to send to my form job reference textbox:
<p><span id="job" value="90192"><strong>Reference Number: 90192</strong></span></p>
//when this link will be clicked it will redirect to apply.html with job value stored in session.
Apply Here
<p><span id="job2" value="90192"><strong>Reference Number:90192</strong></span></p>
//when this link will be clicked it will redirect to apply.html with job value stored in session.
Apply Here
JavaScript file of jobs.js:
"use strict"
function storedata() {
var job = document.getElementById("job").value;
var job2 = document.getElementById("job2").value;
var job3 = document.getElementById("job3").value;
sessionStorage.job = job;
sessionStorage.job2 = job2;
sessionStorage.job3 = job3;
}
function init() {
var apply = document.getElementById("apply");
var apply2 = document.getElementById("apply2");
var apply3 = document.getElementById("apply3");
apply.onclick = storedata;
apply2.onclick = storedata;
apply3.onclick = storedata;
}
window.onload = init;
Here I want to store my job reference number which is from apply.html:
<label for="Job">Job Reference Number</label>
<input type="text" name="Student ID" id="Job" norequired="norequired" pattern="\d{5}" />
<br />
<br />
And this is my JavaScript function for getting the sessionStorage in apply.js:
function retrievedata() {
document.getElementById("Job").value = sessionStorage.Job = Job;
}
The issue is that when click on apply link from jobs.html it will redirect to apply.htm where the job reference number will be stored but it is not happening

Do like this
store data
sessionStorage.setItem("job", "xyz");
retrive
if (sessionStorage.job)
document.getElementById("result").innerHTML = sessionStorage.getItem("job");
Check this also : https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

The problem is you are using anchor tag href to navigate to the apply.html and hence before your method triggering on click gets executed it's going to the apply.html.
<a href='apply.html'>Button</a>
Use something like this
<a id='navigateToApplyPage'>Button</a>
In the JS:
$('#navigateToApplyPage').on('click',function(){
// set sessionstorage //sessionStorage.setItem....
// navigate to the required page // window.location.href = .....
})

Problem is how you are referencing value. There is no value property for non inputs.
var el = document.getElementById("t");
console.log("value: ", t.value); //nope
console.log("getAttribute: ", t.getAttribute("value")) //right
console.log("dataset: ", t.dataset.value) // how most would do it
<span id="t" value="1" data-value="123"></span>
Event better use data-value since that is a valid attribute.
And session storage keys are case sensitive sessionStorage.Job is not the same as sessionStorage.job And this line is wrong.
document.getElementById("Job").value = sessionStorage.Job = Job;
You are storing the variable Job into sessionStorage.Job which is storing Job into the value. It should just be
document.getElementById("Job").value = sessionStorage.job
And after that, you have to figure out what item you clicked.

Related

Why isn't my localStorage.setItem() and localStorage.getItem() storing a value?

I want to store a user input value using localStorage then use that value in my countdown timer.
Here is the HTML where the user inputs their data:
<form action='/' method= 'GET' id='settings'>
<label> Work Time </label>
<input class='settingInput' type='number' id='workInput'>
<label id='short-break'> Short Break </label>
<input class='settingInput' id='shortBreak'>
<label id='long-break'> Long Break </label>
<input class='settingInput' id='longBreak'>
<button id = 'set-values'>Submit</button>
</form>
this is the javascript to store and retrieve the data:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
Here is the codepen for the whole project: https://codepen.io/Games247/pen/XWJqebG
This is my first time using setItem and getItem so I may be overlooking something obvious.
Currently it looks like a pair of brackets is stored in the localStorage where workTimeKey should be.
Your linked code on codepen has a problem, in fact the code posted here corrects said problem.
var workTimeSerialized = JSON.stringify(document.getElementById('workInput'));
The above is your codepen, the problem is you are trying to serialize the HTML element to JSON rather than it's value hence the '{}' you see in your session storage.
You need to ensure it's the value of the input element and not the element itself you serialize. Like i mentioned, your code posted here resolves the issue ;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
Note: Whenever you see '[]' or '{}' in session storage rather than your intended value, you are either passing an object directly or an element in your case.
Edit:
'you are most likely not either'
Your input values should be read in the submit click handler otherwise, you get the value of the input before sumbit and not after
So your code:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
becomes:
submitButton.addEventListener('click', (e) => {
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

How to put Parameter only with Javascript through URL in the website

I am using the software rimacon.
And i am using this URL: http://www.jabra.com.de/Support/warranty-checker
I want to send the Value of the serial number from Javascript (rimacon) into this input of this website: (see picture)
In this website, i click the mouse on the right and click "inspect Element/ Element Untersuchen". I get this HTML-Code:
<input type="text" class="serial-number">
i would like to change this into:
<input type="text" class="serial-number" value="xXx">
then i write URL like:
http://www.jabra.com.de/Support/warranty-checker/?xXx="0QYG06DF3FA"
or i would like to change this CODE into:
<input type="text" class="serial-number" name="PUT-Serial-number">
then i write URL like:
http://www.jabra.com.de/Support/warranty-checker/?PUT-Serial-number="0QYG06DF3FA"
i tried some Code with setAttribute or createAttribute and so on to get this fixed:
for example:
//var x = document.getElementsByClassName("serial-number").href="http://www.jabra.com.de/Support/warranty-checker";
var x = document.querySelectorAll("input.serial-number[href^='http://www.jabra.com.de/Support/warranty-checker']");
var y = x.innerHTML = "value="+seriennummer;
alert("y: "+y);
alert("Länge : "+y.length);
//var attr = document.createAttribute("Value");
//attr.value=seriennummer;
//var attr = x.setAttribute("Value",seriennummer);
//alert("attr: "+attr.value);
// this shall open window and show the serialnumber in this websites
url = escape("http://www.jabra.com.de/Support/warranty-checker");
var hpwindow = window.open("http://xxx:8081/sprungxbrett.php?TARGET="+url);
hpwindow.focus();
This Code is in function of onclick().
Please I need your Help! Is there some way to get fixed this JS-Code!
Because in "Inspect element/Element Untersuchen", you can add Attribute Value into this
<input type="text" class="serial-number" value="0QYG06DF3FA">
then this serial number truly display in the input this website.
Thank you very much.
this should solve getting the URL params as JSON format (wont show anything here, try any test file with url params, ex: test.html?this=that&that=this)
<p id="result"> result: </p>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
//get your values as JSON, one of the following
console.log(map);
document.getElementById("result").innerHTML += JSON.stringify(map);
return map;
}
getUrlVars()
</script>

Resetting/Clearing Form Upon Button Click w/ Firebase

I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!

Get the original url in this case with jquery

In the form below, I change the action attribute and submit the form. That works fine. What goes on is: if the current location is http://localhost/search/?mod=all and the search term is 14, the action will be changed to http://localhost/search/?mod=all&handle=14 and so will the url in the browser.
But the next time I try to search, since the url now is http://localhost/search/?mod=all&handle=14, I get http://localhost/search/?mod=all&handle=14&handle=15. It'll keep going on and on with each search term.
Any idea how I can retain the orginal url http://localhost/search/?mod=all through this all.
Here's the form:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
Here's the jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
There are few ways to do it. I would rather not mess with window.location and do something simpler:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
You have multiple ways to do it. Why can't you store original URL in a global variable (kept outside your functions like form submit etc.)
If you do not want that you can use window.location.hash which will return all the GET params you are sending. Using split you will be able to get exact parameter that you want. If you still need help, I will post the code.
Quickest solution: If, for this code, window.location should always be http://localhost/search/?mod=all, then you don't even need to say var locale = window.location. Just say var locale = "http://localhost/search/?mod=all" and you avoid the problem.
​var s = window.location.hostname; // gets the hostname
var d = window.location.protocol; // gets the protocol
var g = window.location.search; // gets all the params
var x = g.split("&"); // split each parameter
var url = d+"//"+s+x[0]; // makes url you want
alert(url);​​​​ // just for chill

Categories

Resources