why does my innerHTML vars don't add correct? - javascript

Ok so it does add, but not right
So my vars think that they are text but I want just the nums, so I can add them together.
How do I do this?
a fiddle to see whats so wrong
<html>
<head>
<title>Nose Clicker</title>
<style>
body{
background-image:url("https://i.pinimg.com/originals/66/27/70/6627703d20110ad2e8877fab5fc102b9.jpg");
}
#root-SuperGloabalVar1{
color: red;
font-size: 150px;
padding: 0px;
}
#var-wrapper{
opacity: 0%;
}
</style>
</head>
<body>
<div id = 'var-wrapper'>
<h1 class = 'vars' id = 'perclick'>
<---here is the first addend--->
1
</h1>
</div>
<---here the second one--->
<h1 id = 'root-SuperGloabalVar1'>0</h1>
<img onclick = '
<---get number 1--->
var v = getElementById("root-SuperGloabalVar1");
<---get number 2--->
var a = getElementById("perclick");
<---adding--->
var w = v.innerHTML+=a.innerHTML;
<---replacing and then it shows "01"--->
v.innerHTML(parrseint(a.innerHTML + v));
'
src = 'https://www.pngitem.com/pimgs/m/155-1559954_cartoon-nose-images-cartoon-nose- image-png-transparent.png'>
</body>
</html>

I didn't completely understand your question can you explain it a bit more and detailed but if you want to parse text into number then use
var x = a.innerHTML;
Number(x)
Edit:
And a proper way to use number increment and display it is like this:
(you don't need to save your integer in an element you can use a javascript variable)
let clicks = 0;
function countClicks() {
clicks++;
const display = document.getElementById("display");
display.innerHTML = clicks;
}
<!DOCTYPE html>
<html lang="en">
<body>
<div style="background: red; width: 100px; height: 100px;" onclick="countClicks();">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>
</html>
Example to use in onclick callback:
<body>
<script>var clicks = 0;</script>
<div style="background: red; width: 100px; height: 100px;"
onclick=
"
clicks++;
const display = document.getElementById('display');
display.innerHTML = clicks;
">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>

Related

JavaScript using indexOf and lastIndexOf to put setattribuit

I want to use indexOf() and lastIndex() to add attributes by setAttribute after customizing the URL.
I try this code but not working:
<!DOCTYPE html>
<html>
<head>
<style>
#two {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 50px;
}
</style>
<title></title>
</head>
<body>
<select onchange="check()" id="selectbox" name="">
<option hidden value="empty"></option>
<option value="first">1</option>
<option value="second">2</option>
</select>
<div id="two">
<div id="de6854">
<div style="width: 100%;height: 100%">
<iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100" style="width: 100%; height: 100%">
</iframe>
<iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100" style="width: 100%; height: 100%">
</iframe>
</div>
</div>
</div>
</body>
<script>
function check(){
var val = document.getElementById("selectbox").value
var pic = document.querySelectorAll("#two iframe")
var s = val.substring(0, val.indexOf('?resize='));
var ss= val.substring(val.lastIndexOf(',10'));
var f = s + ?resize= + '400' + ss;
var s = s + ?resize= + '500' + ss;
if(val==="first"){
pic.setAttribute('src','f')
} else if(val==="second"){
pic.setAttribute('src','s')
}
}
</script>
</html>
Any one can find solution of that problem:
I test write that code in JavaScript and running good:
var s = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
s = s.substring(0, s.indexOf('?resize='));
document.write(s);
document.write('<br>');
document.write('<br>');
var ss = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
ss = ss.substring(ss.lastIndexOf(',10'));
document.write(ss);
document.write('<br>');
document.write('<br>');
rr = s+"?resize="+"500"+ss
document.write(rr);
this code give result: https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=500,100
change 200 and add 500.
second code after some answers:
not the ID in frame in changed every load page, like that: <iframe id="3ad34"
code:
<!DOCTYPE html>
<html>
<head>
<style>
#twoposition {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 50px;
}
</style>
<title></title>
</head>
<body>
<select onchange="check()" id="selectbox" name="">
<option hidden value="empty"></option>
<option value="firstSize">1</option>
<option value="secondSize">2</option>
</select>
<div id="two">
<div id="de6854">
<div style="width: 100%;height: 100%">
<iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
</iframe>
<iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
</iframe>
</div>
</div>
</div>
</body>
<script>
function check() {
var val = document.getElementById("selectbox").value
var pic = document.querySelectorAll("#two iframe")
var aa = pic.getAttribute('src')
const url = new URL(aa);
url.searchParams.set('resize', '500,200');
if(val === "firstSize") {
pic.setAttribute('src', ff)
}
else if(val === "secondSize") {
pic.setAttribute('src', ff)
}
}
</script>
</html>
You can simply use an URL() constructor and set the URL.searchParams on it as needed.
const inputUrl = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
const url = new URL(inputUrl);
url.searchParams.set('resize', '500,200');
console.log(url);
Example assigning it to an attribute.
function addImgWithSize(inputUrl, width=300, height=200){
const url = new URL(inputUrl);
url.searchParams.set('resize', [width, height]);
// assigning it to the 'src' attribute
const img = document.createElement('img');
img.src = url;
document.body.append(img);
}
const exampleUrl = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100'
addImgWithSize(exampleUrl, 500, 200)
addImgWithSize(exampleUrl, 30, 20)

Get string content of HTML input

I have an HTML form that will contain predefined values that the user will have to confirm by editing their contents, if needed.
I would like to perform a constant check so that the color background of every cell changes accordingly to its content.
For example, if the cell is empty, its background should be red. Later on I will add more check, for example if it contains the string "MISSING VALUE" it should be yellow and so on.
This is an example of my form and the code I'm trying to execute:
<!DOCTYPE html>
<html>
<style type="text/css">
table.first {
display: table;
table-layout: auto;
float: none margin-left: auto;
margin-right: auto;
}
.table_element {
display: table-cell;
}
</style>
<table class="first">
<div class="table_element">
<p style="text-align: center;">First Name:<br><input name="import_date_visit" id="subEmail" type="text" required size="25" onchange="checkFilled();" value="Claudio"></p>
</div>
<div class="table_element">
<p style="text-align: center;">Last name:<br><input name="import_date_visit" type="text" required size="25" onchange="checkFilled();" value="MISSING VALUE"></p>
</div>
</table>
<script type="text/javascript">
function checkFilled() {
var inputVal = document.getElementsByClassName("table_element");
for (var i = 0; i < inputVal.length; i++) {
document.writeln((i + 1) + ": " + inputVal[i].value);
}
for (var i = 0; i < inputVal.length; i++) {
if (inputVal[i].value == "") {
inputVal[i].style.backgroundColor = "red";
} else {
inputVal[i].style.backgroundColor = "white";
}
}
}
checkFilled();
</script>
</html>
What I don't understand is how to get the value of the string inside the div element. As you can see, I'm trying to print it as a debug, and I'm expecting to get the values Claudio and MISSING VALUE, but all I get is undefined. I suppose it should be pretty straightforward to get the content of a cell, so I assume I'm missing something very obvious.
Thanks for the help.
First find input element inside your div element and then use value property on it.
function checkFilled() {
const divEle = document.getElementsByClassName("table_element");
for(let i = 0; i < divEle.length; i++) {
const inputVal = divEle[i].children[0].children[1];
if (inputVal.value == "") {
inputVal.style.backgroundColor = "red";
} else if (inputVal.value == "MISSING VALUE") {
inputVal.style.backgroundColor = "green";
}
}
}
checkFilled();
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table.first{
display: table;
table-layout: auto;
float:none
margin-left: auto;
margin-right: auto;
}
.table_element{
display: table-cell;
}
</style>
</head>
<body>
<table class="first">
<div class="table_element">
<p style="text-align: center;">First Name:<br>
<input name="import_date_visit" id="subEmail" type="text" required size="25" onchange="checkFilled();" value="Claudio" />
</p>
</div>
<div class="table_element">
<p style="text-align: center;">Last name:<br><input name="import_date_visit" type="text" required size="25" onchange="checkFilled();" value="MISSING VALUE" /></p>
</div>
</table>
</body>
</html>
Firstly, you should always have a body element. Whenever you create anew HTML document, you should first paste in the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Scripts and stylesheets should go into the head section, and any content that should be visible to the user in to the body section. <meta charset="utf-8"> should be always present - else non-ASCII characters will not be rendered correctly. Change utf-8 to whatever encoding you use in your editor.
Secondly, inputVal[i].value tries to access the value property of the p element in side .table_element - but paragraphs don't have a value, so you get undefined.
Thirdly, document.write and document.writeln should not be used - if you want to show something to the user, write it into a HTML element, and if you want to print something for debugging purposes, use console.log(...).
Lastly, div's are not valid children of a table - only thead, tbody and tr are.
To find the input elements, you can use document.querySelectorAll. Following the working, modern code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
table.first {
display: table;
table-layout: auto;
float: none;
margin-left: auto;
margin-right: auto;
}
.table_element {
display: table-cell;
}
</style>
<script type="text/javascript">
function checkFilled() {
let inputElements = document.querySelectorAll(".table_element input");
let outputElement = document.querySelector("#output");
outputElement.innerHTML = "You entered : ";
for (let [index, inputElement] of inputElements.entries()) {
outputElement.innerHTML += " " + (index + 1) + " " + inputElement.value;
if (inputElement.value == "") {
inputElement.style = "background-color: red;";
} else {
inputElement.style = "background-color: green;";
}
}
}
window.addEventListener("load", checkFilled);
</script>
</head>
<body>
<div class="table_element">
<p style="text-align: center;">First Name :</p>
<input name="import_date_visit" id="subEmail" type="text" required size="25" oninput="checkFilled();" value="Claudio">
</div>
<div class="table_element">
<p style="text-align: center;">Last name :</p>
<input name="import_date_visit" type="text" required size="25" oninput="checkFilled();" value="MISSING VALUE">
</div>
<p id="output">You entered : nothing yet</p>
</body>
</html>

Javascript hide picture

I use these flashcards quite regularly. Lately, I have been using pictures as answers. However -I cannot hide the pictures. I would like for the pictures to be hidden upon webpage startup.
function myShowText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'black';
}
function myHideText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'white';
}
.answer {
border-style: solid;
border-color: #287EC7;
color: white;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Flashcards VBA </title>
<rel="stylesheet" href="css/styles.css">
</head>
<body>
<script src="js/scripts.js"></script>
<h3> Flashcards </h3>
<p class="question">
The first question
</p>
<div id="bash_start">
<p class="answer">
<img src="image.jpg">
</p>
</div>
</body>
</html>
Just add the following CSS class:
.hidden {
display: none;
}
and add the class .hidden to your answer:
<p class="answer hidden">
<img src="image.jpg">
</p>
Then remove this .hidden class whenever your want to show the answer:
document.querySelector('.answer').classList.remove('hidden');
Here is a working example:
var button = document.querySelector('button');
var answer = document.querySelector('.answer');
button.addEventListener('click', function() {
answer.classList.remove('hidden');
});
.hidden {
display: none;
}
<button type="button">Show answer</button>
<p class="answer hidden">This is the answer</p>
If I understand correctly you just want your image to be hidden when the user load the page ? In that case juste put somme css on your image(s) visibility: hidden; or display: none;
Then Javascript/Jquery side you do whatever event you want to fire it and change visibility: visible; or display: block/inline-block;.
<img class="flashCards" src="https://cdn4.iconfinder.com/data/icons/champions-1/512/Champions-04-512.png">
<button id="validate_btn" onclick="validate()">Validate</button>
<style>
img.flashCards { width: 150px; visibility: hidden; }
</style>
<script>
function validate() {
var flashCards = document.getElementsByClassName('flashCards');
//Need a for loop for each image element
//If only one image use getElementById directly with the style
for(i=0;i<flashCards.length;i++) {
flashCards[i].style.visibility = 'visible';
flashCards[i].style.backgroundColor = 'green';
}
}
</script>

Remove <div> elements created by Javascript by using javascript

My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});

How to write html with javascript and display it on a slider?

I have created a basic slider that runs through images every 5 seconds while using javascript. My slider works just fine, but I'm not wanting to use it as an image slider anymore. I'm wanting to create a div with some more html design features and post that within my slider instead of my images. Going by this code below, what would I have to change and add to make it work?
<!doctype html>
<html>
<head>
<title>Ad Slider</title>
<style>
#slider
{
width: 800px;
height: 200px;
}
#sliderImages
{
width: 100%;
height: 100%;
border: 1px solid #06c;
border-radius: 10px;
}
</style>
<script type = "text/javascript">
var image1 = new Image();
image1.src = "sky.jpg";
var image2 = new Image();
image2.src = "chatImage.jpg";
var image3 = new Image();
image3.src = "orange.jpg";
</script>
</head>
<body>
<div id = "slider">
<img id = "sliderImages" src = "sky.jpg" name = "slide" />
<script type = "text/javascript">
var sliderAd = 1
function slideAds()
{
if (!document.images)
{
return;
}
document.images.slide.src = eval("image"+sliderAd+".src")
if (sliderAd < 3)
{
sliderAd++;
}
else
{
sliderAd = 1;
}
setTimeout("slideAds()",5000)
}
slideAds()
</script>
</div>
</body>
</html>
Now instead of adding those images, how can I add this type of content but working the same way like the images were?
<div>
<p>Some Content</p>
</div>
There are plenty of ways to write what you're looking for. Here's an augmented version of your code... You can toss whatever HTML you want into the innerHTML.
In the future, you're better of using Google to read up on the basics of Javascript...
<div id = "container">
</div>
<script type = "text/javascript">
MAXSLIDES = 2
slideText = 1
function slideAds() {
container = document.getElementById("container")
if(slideText == 1) {
container.innerHTML = "test1"
} else if (slideText == 2) {
container.innerHTML = "test2"
}
slideText += 1
if(slideText > MAXSLIDES) { slideText = 1 }
setTimeout("slideAds()",5000);
}
slideAds()
</script>
One of the easiest way is just to create an array of html you need, and than iterate through it inserting in each string as html in your holder div: here is an example from your question the only thing I used jQuery it is much easier that way.
<!doctype html>
<html>
<head>
<title>Ad Slider</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style>
#slider
{
width: 800px;
height: 200px;
}
#sliderImages
{
width: 100%;
height: 100%;
border: 1px solid #06c;
border-radius: 10px;
}
</style>
<script type = "text/javascript">
var arrayOfDiv = new Array();
arrayOfDiv[0] = "<div style='background-color:#FF0'>this is first div!</div>";
arrayOfDiv[1] = "<div style='background-color:#0ff'>this is second div!</div>";
arrayOfDiv[2] = "<div style='background-color:#f0f'>this is third div!</div>";
var sliderAd = 0;
function slideAds()
{
$("#sliderImages").html(arrayOfDiv[sliderAd]);
if (sliderAd < arrayOfDiv.length-1)
{
sliderAd++;
}
else
{
sliderAd = 0;
}
setTimeout("slideAds()",5000);
}
$(function(){
slideAds();
});
</script>
</head>
<body>
<div id = "slider">
<div id = "sliderImages" ></div>
</div>
</body>
</html>

Categories