localStorage clears screen - javascript

I'm testing out localStorage to see if it can be used in my app, but when I try to store data from a text input box to it, the screen goes blank. How can I fix this? Here is the code:
<html>
<head>
<script type="text/javascript">
function write() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display').innerHTML = data;
}
</script>
</head>
<body>
<input id="input" type="text" />
<button type="button" onclick="write()">
Write
</button>
<p id="display">
Display
</p>
<button type="button" onclick="read()">
Read
</button>
</body>
</html>

change your function name from write to something else. it sounds like you are accidentally invoking document.write, which would blank out your entire page.

You cannot use a function called write on the global (document) namespace ... call it something else and it works fine
<input id="input" type="text" />
<button type="button" onclick="somethingelse();">
Write
</button>
<p id="display1">
Display
</p>
<button type="button" onclick="read()">
Read
</button>​
function somethingelse() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display1').innerHTML = data;
}​
Working example here

The code inside html event handlers is ran effectively like:
with(document) {
with(this) {
write();
}
}
so your write is shadowed (it calls document.write). You can simply refer to the correct write with window.write():
<button type="button" onclick="window.write()">
Ultimately it's better not to use inline html events at all. A simple button.onclick = write would have worked, where button is reference to the element.

Related

Onclick function error, function isn't defined

Over the recent days 've been trying to make buttons that changes a text's color by using
document.querySelector.('class name').style.color
in a function while using onclick to put that function in the button, but it always says my function *chanageColor isn't defined. Could some of you help me please? It also says theres an unexpected token, please help me with that as well!
<body>
<div class="box">
<h1> Hello</h1>
</div>
<script>
function changeColor(){
document.querySelector.('.box').style.color = 'pink';
}
</script>
<button class="pink">Pink</button>
</body>
</html>
Well, there's nothing in your code here that would even try to call your function so I can't say for sure what your issue is, but to hook up the click event of the button to your function, you use: .addEventListener().
Now, you do have a typo:
document.querySelector.('.box') // <-- The dot before ( is wrong
And your script element should be the last thing before you close the body tag so that by the time the script runs, all the HTML will have been parsed into memory.
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
document.querySelector('.box').style.color = 'pink';
}
</script>
And while this works, inline styles should be avoided whenever possible because they are the hardest type of CSS styling to override and lead to duplication of code. Instead, use CSS classes whenever you can (almost always) as shown here:
.pinkText { color:pink; }
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
// Get your DOM element references just once, not every time the function runs:
const box = document.querySelector('.box');
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
box.classList.add('pinkText');
}
</script>
<!DOCTYPE html>
<html>
<body>
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink" onclick="changeColor()">Pink</button>
</body>
<script>
function changeColor(){
document.querySelector('.box h1').style.color = 'pink';
}
</script>
</html>

Javascript - strange behaviour naming a function 'submit()'

Is submit a reserved word in Javascript?
Take a look at this code:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="submit()">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
</body>
</html>
I'm trying to understand why I can't call the submit() function inside the <form> tag but it works outside the tag. I think it is a reserved word even because changing the function name the script works well but I can't find any information about that on mdn
I'm not a JS guru, so can someone help me understand this strange behaviour?
The problem is that submit() is a built-in function that gets called whenever a <form> gets submitted. To have custom functionality kick in which a form is submitted, you'll not only need to use a different function name, but also prevent the default form submission with event.preventDefault(), passing the event into the function.
This can be seen in the following -- note that the sayHello() will clear the screen (with an attempted form submission), whereas customSubmit() will not:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function customSubmit(e){
e.preventDefault();
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="customSubmit(event)">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="customSubmit(event)">Submit - outside</button>
</body>
</html>
Buttons inside forms automatically submit the form, as long as the button doesn't have an event handler, or has an event handler that doesn't preventDefault():
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
(see how the form gets submitted - the page in the snippet disappears)
It has nothing to do with the submit function name.
But still, using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener.
Inline handlers should be avoided just as much as eval should be avoided.
If you want to prevent a button inside a form from submitting the form, call e.preventDefault() like this:
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
const [b1, b2] = Array.from(document.querySelectorAll('button'));
b1.addEventListener('click', (e) => {
e.preventDefault();
sayHello();
});
b2.addEventListener('click', (e) => {
e.preventDefault();
submit();
});
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
Pressing a button in a form reloads the page.
<html>
<head>
</head>
<body>
<!--Any button in the form will submit the form and reload the page-->
<form>
<button id="btn1">Say hello</button>
<button id="btn2">Submit</button>
<button>Anything</button>
</form>
<!--these ones don't-->
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
<script>
// notice the page loads when we click the 'anything' button, even without an event handler
//the delay allows you to see it happening
console.log("loading page...");
setTimeout(welcome, 500);
function welcome() {
console.log("page has been loaded");
}
// adding preventDefault to these, stops the form from submitting
function sayHello(e) {
console.log('Hello!');
e.preventDefault();
}
function submit(e) {
console.log('Submit!')
e.preventDefault();
}
//This is how you add event handlers
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
btn1.addEventListener('click', sayHello);
btn2.addEventListener('click', submit);
</script>
</body>
</html>

Trying to change a link on button click with javascript

I have three buttons and i want such tha when i click on one button the link on an a tag changes
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="goldpac">Choose Plan</button>
<button class="silverpac">Choose Plan</button>
<button class="bronzepac">Choose Plan</button>
I want such that when i click on one button, it changes the link at .payverlink
I have tried
function bronze()
{
$('.payverlink').href="exbronzeregistrationform.php";
}
function silver()
{
$('.payverlink').href="exsilverregistrationform.php";
}
<button class="silverpac" onclick="silver()">Choose Plan</button>
<button class="bronzepac" onclick="bronze()">Choose Plan</button>
But this changes to bronze function onclick of any of the buttons. Please whats the issue.
You could set your javascript code to trigger the button click and avoid using the onclick into html
$(document).ready(function() {
$("button").on('click', function(){
if ($(this).hasClass('goldpac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
} else if ($(this).hasClass('silverpac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
} else if ($(this).hasClass('bronzepac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
}
});
});
You could add one more line in each case changing the a tag, but ti wont make a huge difference in your actions as it isn't used as you click the buttons.
$("a.payverlink").attr("href", "http://...."); /* or exbronzeregistrationform.php for example */
So, you could just remove the 'href' as you contantly will change the url from js.
Use attr or prop, attr stands for attribute and prop for property!
$(
function(){
$('#google').attr('href', 'https://duckduckgo.com/');
//or use prop
$('#duckduckgo').prop('href', 'https://bing.com')
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Learning</title>
</head>
<body>
<h1 class="header"></h1>
<a id="google" href="https://google.com/">google is down!</a>
<br>
<a id="duckduckgo" href="https://duckduckgo.com/">I'm slow...</a>
</body>
</html>
I suspect that both functions are failing, since there is no such property href on JQuery object.
Use this approach instead:
$('.payverlink').prop("href","exbronzeregistrationform.php");
Have you try .prop() method of jQuery hopefully it works .
function bronze()
{
$('.payverlink').prop('href','exbronzeregistrationform.php');
}
function silver()
{
$('.payverlink').prop('href','exsilverregistrationform.php');
}
You can use the .attr function:
function bronze(){
changeLink('exbronzeregistrationform');
}
function silver(){
changeLink('exsilverregistrationform.php');
}
function changeLink(url){
$('.payverlink').attr('href',url);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="silverpac" onclick="silver()">Choose Plan silverpac</button>
<button class="bronzepac" onclick="bronze()">Choose Plan bronzepac</button>
function bronze()
{
$('.payverlink').attr("href","exbronzeregistrationform.php");
}
function silver()
{
$('.payverlink').attr("href","exsilverregistrationform.php");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="goldpac">Choose Plan</button>
<button class="silverpac" onclick="silver()">Choose Plan</button>
<button class="bronzepac" onclick="bronze()">Choose Plan</button>
You can try this. it will helps you. :)

Check what exatly button clicked, when multiple buttons with the same selector on page

I have a two buttons with the same selector class. When I do this:
$('.my_button').click(function() {
console.log(1);
});
, and then click on the button it log 1 two times, like I clicked both buttons instead single. So my question is: There exists some way in JS to get only that button what I clicked, without assign unique selector like id. I am newbien in JS, so can somebody explain me? I found related issue here. Thanks!
Edit:
I make buttons a little bit different. And yes, it returns only single button, but why click trigger works two times. Console log log two times.
Every event listener receives the event, which carries the event target. Try the below example.
$('.my_button').click(function(e) {
console.log(e);
console.log(e.currentTarget);
console.log($(e.currentTarget));
});
use this inside your function code
$('.my_button').on('click',function() {
var tempContainer=$(this).parent();
alert($(tempContainer).html()); // you ll see that you are showing the code where exists your clicked button
});
Assign different id to your buttons
$(".my_button").on("click",function(){
console.log($(this).attr("id"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="my_button" id="test" value="Test"/>
<input type="button" class="my_button" id="test2" value="Test-2"/>
Try this:
<button class="my_button">Content1</button>
<button class="my_button">Content2</button>
<script>
$( ".my_button" ).click(function( event ) {
console.log(1);
});
</script>
https://jsfiddle.net/nt9ryeyr/5/
Try this:-
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".p").click(function(e){
alert($(e.currentTarget).attr("value"));//button text on which you clicked
});
});
</script>
</head>
<body>
<input type='button' class="p" value='test'/>
</body>
</html>
if your html is like this
<button class="my_button">Test</button>
<button class="my_button">Test1</button>
then use this script
$('.my_button').click(function() {
if(this.innerHTML ==="Test")
console.log(1);
else
console.log(2);
});
or if your html is like this
<input type="button" class="my_button" value="Test"/>
<input type="button" class="my_button" value="Test1"/>
then use this script
$('.my_button').click(function() {
if($(this).val() ==="Test")
console.log(1);
else
console.log(2);
});

How to make a button visible by clicking another button?

How can I make the button save visible when I click the edit button? This is my code so far, but it happends nothing. I'm working in a jsp
<INPUT TYPE="BUTTON" VALUE="Edit" ONCLICK="btnEdit()" class="styled-button-2">
<INPUT TYPE="BUTTON" VALUE="Save" ONCLICK="btnSave()" class="styled-button-2" style="visibility:hidden;" id="save">
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementsById("save").style.visibility="visible";}
}
</script>
DEMO
It is considered bad practice to add onclick in your html, and you miss-spelled a method. You should equally avoid adding your css in your html as well.
HTML:
<INPUT TYPE="BUTTON" VALUE="Edit" class="styled-button-2" id="edit">
<INPUT TYPE="BUTTON" VALUE="Save" class="styled-button-2" id="save">
JS:
var edit = document.getElementById("edit");
var save = document.getElementById("save");
edit.onclick = function() {
save.style.visibility = "visible";
}
CSS:
#save {
visibility: "hidden";
}
Must be a long day.
You have a misspelling.
Not right
document.getElementsById
Right Way
document.getElementById
document.getElementById("save").style.visibility="visible";
use getElementById not getElementsById
Probably a simple error, but you wrote getElementsById not getElementById, which meant you were trying to get more than one element, when infact you only need to get the "save" button.
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementById("save").style.visibility="visible";}
}
</script>
Side note: You may want to tidy your code:
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
document.getElementById("save").style.visibility="visible";
}
</script>

Categories