javascript query selector and const issue - javascript

hope you can clarify an issue I am having that is driving me crazy:
I am trying to get te value of the inpt "#size" in JS, I am using the comand:
submit.addEventListener('click', function(e){
document.querySelector('#output').innerHTML = document.querySelector('#size').value;
document.querySelector('#size').value = '';
})
it works like this, but the thing is that i can not declare the variables to make my code shorter and to handle the data latter, if I use:
const submit = document.querySelector('#submit');//refers to the button to activate the event listener
submit.addEventListener('click', function(e){
document.querySelector('#output').innerHTML = document.querySelector('#size').value;
document.querySelector('#size').value = '';
})
it does not get any value from the size, console says:
Uncaught SyntaxError: Identifier 'submit' has already been declared
it is an error that is happening often and I still not able to solve, hope some of you guys an clarify what am I doing wrong.
EDIT:html code below:
<body>
<input type="text" id="size">
<button id="submit">Sumbit</button>
<ul id="output">
</ul>
<script src="functtions.js"></script>
</body>```
thanks

You certainly have another variable called submit somewhere else. Using function usually prevent such variable collision problem, so what about this kind of code?
function () {
let submit = document.querySelector('#submit');
let size = document.querySelector('#size');
let output = document.querySelector('#output');
submit.addEventListener('click', function(e){
output.innerHTML = size.value;
size.value = '';
});
}();

Related

Saving some contenteditables localstorage - - -

I'm trying to save more than one entry of contenteditable content into my localstorage for a Chrome extension. My current code saves just one contenteditable section fine, but when I try to add another Id of a seperate contenteditable section it either deletes all the saved information or doesn't do anything at all. I'm pretty novice in JS, so I hope I'm just making a simple mistake. My html looks like this:
<div id = "content">
<div id= "tcontent" contenteditable="true" data-ph=" Make a note . . . "
style= "height: 300px; overflow: auto"></div>
<div id = "content2">
<div id= "tcontent2" contenteditable="true" data-ph= " Make a note . . . "
style= "height: 300px; overflow: auto"></div>
</div>
And this is my Javascript:
window.addEventListener('load', onLoad); function onLoad() {
checkEdits();
}
function checkEdits() {
if(localStorage.userEdits!=null) {
document.getElementById("tcontent", "tcontent2").innerHTML += localStorage.userEdits;
}
};
document.onkeyup = function (e) {
e = e || window.event;
console.log(e.keyCode);
saveEdits();
};
function saveEdits() {
var editElem = document.getElementById("tcontent", "tcontent2");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
};
Basically this code will only save one (the content I place first into the getElementbyId). Isn't there a way to save both of the 'content's?
I've been playing around with all my little knowledge of javascript I have but can't seem to see what I'm doing wrong or what I should be doing here.
Much thanks for any and all help.
document.getElementById is a method that only takes one element's id. You are currently trying to pass two strings to the method. That will not work.
Please refer to the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Also, you must assign the innerHTML of each element individually to each piece of saved content in localStorage.
Granted that you are fairly new to the Language I do not want to overcomplicate the answer for you. With that said, please find below your code with a few modifications to be able to save both pieces in localStorage respectively:
window.addEventListener('load', onLoad); function onLoad() {
checkEdits();
}
function checkEdits() {
if(localStorage.userEdits1!=null) {
document.getElementById("tcontent").innerHTML = localStorage.userEdits1;
}
if(localStorage.userEdits2!=null) {
document.getElementById("tcontent2").innerHTML = localStorage.userEdits2;
}
};
document.onkeyup = function (e) {
e = e || window.event;
console.log(e.keyCode);
saveEdits();
};
function saveEdits() {
var editElem1 = document.getElementById("tcontent");
var editElem2 = document.getElementById("tcontent2");
localStorage.userEdits1 = editElem1.innerHTML;
localStorage.userEdits2 = editElem2.innerHTML;
};

How to use event listener in JS

Im trying to use the same buttons for different function in the program. So I tried using event listeners but for some reason its not working. Could look at the code and tell me what I have done wrong? Thanks. (I omited the HTML tags and so for shortening the posted code)
<script type="text/javascript">
var photo = "photo";
var edgar = "edgar"
var x = document.getElementById("yes");
x.addEventListener("click", choiceyesstory);
x.addEventListener("click", choiceyesfriendly);
var y = document.getElementByID("no");
y.addEventListener("Click", choicenostory);
y.addEventListener("click", choicenofriendly);
function choiceyesstory(x) {
document.getElementById("photo").src = "images/dragon1.jpg";
document.getElementById("stage1").innerHTML = "Once upon a time";
setTimeout("choice2()",5*1000);
}
function choicenostory(y) {
document.getElementById("photo").src = "images/sea.jpg";
document.getElementById("stage1").innerHTML = "Would you like to
listen to some music?";
document.getElementById("edgar").play();
}
function choice2(x){
document.getElementById("photo").src = "images/dragon9.jpg";
document.getElementById("stage1").innerHTML = "Was he a friendly
dragon?";
}
function choiceyesfriendly(x) {
{document.getElementById("photo").src = "images/dragon2.jpg";
document.getElementById("stage1").innerHTML = "He had many friends";
}
function choicenofriendly(y)
{ document.getElementByID ("photo").src = "images/dragon3.jpg";
document.getElementById("stage1").innerHTML = "He did so and so";
}
</script>
<body>
<button id="yes">Yes</button>
<button id="no">No</button>
</body>
Edit / Delete Edit Post Quick reply to this message Reply Reply With Quote Reply With Quote Multi-Quote This Message
Reply to Thread
Quick Navigation DOM and JSON scripting Top
Quick Reply Quick Reply
I took yours js and simplified it. The event listener by itself is working ok. Maybe you have issue somewhere else.
http://jsfiddle.net/jnmav1wk/
var x = document.getElementById("yes");
console.log(x);
x.addEventListener("click", choiceyesstory);
function choiceyesstory(x) {
alert('Clicked');
}
Try to simplify your problem, get rid of the NO and all corresponding code, keep removing code till it's working. Then add feature by feature till it will stop working and you know where it's broken.
I use console.log(); and alert(); to make it more verbose to me.
Sometimes the code needs to be inside this:
$( document ).ready(function() {
yourCode();
});
This needs jQuery, if you want avoid it, here are some alternatives:
$(document).ready equivalent without jQuery
Because if the functions are executed against HTML code which is in middle of loading (and maybe the YES button is not there yet while you try to attach the event listener to it, etc...)

How to change the function called by a dynamically created button?

I was making a little game in JavaScript when I ran into a problem. In this game I create a hundred buttons using a for() loop. Eventually I want every button to call a function called 'click' and send it an int so it knows what button is pressed. So for instance when button four is pressed click(4) is called. First I tried this:
object.onclick = "click(4)";
That obviously didn't work so i searched the interwebs and fount an answer to this question on your site.
object.onclick = function() {click("4");}
I tried that (with and without the ';' at the end) but it doesn't seem work.
A more complete overview of the dummy code:
<script type="text/javascript">
document.getElementById('myContainer').innerHTML += '<input id="tmp" type="button" value="button">';
documengetElementById('tmp').onclick = function() {tmpFunc("bla");}
function tmpFunc(vari){
alert(vari);
}
</script>
The element myContainer is 100% empty!
Remember, this is just dummy code to try it out. I could do this waaaaay easier but I tried to simplify it first so you don't have to look at my messy code.
So what is the best way to call a function from a button you have created in a for loop? If you know a way to do it totally different from the one I use just post it, I don't care how it gets solved! Although I'd also like somebody to explain why this isn't working.
Hope I didn't ask a question already answered, as far as I know I'm using the solution given for this problem in another post.
------------UPDATE-------------
Changed it a bit after getting an answer from somebody. This is the current code, select() isn't executed when a button is pressed. Here's the complete JavaScript code so you can copy-paste it if you want to play around with it.
<script type="text/javascript">
function addButtons(){
var disabled = false;
for(var i = 1; i <= 100; i++){
currentButton = '<input id="tmp" type="button" onclick="select(\''+i+'\')">'
document.getElementById('myContainer').innerHTML += currentButton;
document.getElementById('tmp').id = 'btn'+i;
gb(i).disabled = disabled;
gb(i).style.width = "60px";
gb(i).style.height = "60px";
gb(i).style.fontSize = "25pt";
function alerts(nr){
alert("test");
}
if(i%10 == 0){
document.getElementById('myContainer').innerHTML = document.getElementById('myContainer').innerHTML + '<br />';
}else{
if(disabled){
disabled = false;
}else{
disabled = true;
}
}
if(i == 60){
gb(i).value = 'O';
gb(i).style.color = "blue";
}
if(((i-1)%10 == 0) && !(gb(i).disabled)){
gb(i).value = 'X';
gb(i).style.color = "red";
}
}
}
function select(nr){
alert("Bla!"+nr);
gb(nr).style.height = "100px";
}
function gb(ButtonNrVanHetButton){
return document.getElementById('btn'+ButtonNrVanHetButton);
}
addButtons();
</script>
Most parts aren't very interesting for solving the problem (style etc) It's supposed to look like a checkerboard.
------------UPDATE-------------
Solved! Don't use functions the javascript library already uses for other stuff like: 'select()'. Thx to everybody who tried to help!
If you are looping to create the buttons, why don't you add an onclick to the button?
for instance
<script>
// your function
function tmpFunc(vari)
{
alert(vari);
}
// end your function
// define xBUTTONS
xBUTTONS = '';
for (i=0; i<100; i++)
{
// loop buttons
xBUTTONS += '<input id="tmp" type="button" value="button" onclick="tmpFunc(\''+i+'\')">';
}
// insert buttons into myContainer
document.getElementById('myContainer').innerHTML = xBUTTONS;
</script>
first off, always attach events by using addEventListener. second, if you add an id to the button you dynamicly generate you can do something like this;
function click(){
alert(this.id+" clicked");
}
var but;
for (var i=0,e=100,i<e;++i){
but=document.createElement("input");
but.id=i;
...//make it into your button
but.addEventListener("click", click, false);
document.body.appendChild(but);
}

Modifying a link with user input

I'm working with a little chunk of code for a function, that I actually picked up in a different question's answer, which was a huge help. Though, trying to modify that snippet of script has been giving me some trouble: I'm trying to change this bit so that instead of changing displayed text with a link, it will modify the link with either static text (like "Click here") or a button element.
<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>
<script type="text/javascript">
var link= document.getElementById('reflectedlink');
var input= document.getElementById('searchterm');
input.onchange=input.onkeyup= function()
{
link.search= '?q='+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
I would really like to have it a simple button that opens the modified link in a new window. I've tried looking for similar solutions and I'm sure I'm missing it just because I have no idea what I'm looking for.
Modified your fiddle:
HTML
Search <input id="searchterm" type="text" />
JavaScript
var searchterm = document.getElementById('searchterm');
var base_url = 'http://www.google.com/search?q=';
searchterm.onchange = searchterm.onkeyup = function(e) {
e = e || event;
if ( (e.which || e.keyCode) == 13 ){
window.open(base_url + encodeURIComponent(searchterm.value), '_blank');
}
};
More info about the window.open function is here.

New to JavaScript and need help on my first program

I'm trying to add a function to my website so when the user clicks on a footnote the browser will display it inline. Here is how far I have gotten,
var locate= document.getElementById("footnote1");
var note= document.getElementById("footnotes2");
function footnote() {
locate.onclick= note.style.display="inline";
};
any help would really be appreciated.
Here is an example of what you want.
var locate = document.getElementById("footnote1");
var note = document.getElementById("footnotes2");
locate.onclick = function() {
note.style.display = "inline";
};
Working Example
http://jsfiddle.net/v8fHE/
you just had to wrap the onclick action in a function
trigger.onclick=function(){toChange.style.background="#FF0000"};

Categories