create multiple arrays on different elements - javascript

I'm trying to set a function in my application which allows the user to click on a button and then click the submit button which displays an image, but I want the buttons to hold more than one image and randomly select an image from the array.
How can I do this?
<div id='prefPage'>
<header id='header2pref'>
<div id='title2pref'>PREFERENCES</div>
</header>
<div id='body'>
<div id='leftAlign'>
<div id="foodpicloc">
</div>
</div><button id='myBtn2'>SET PREFRENCES</button>
<div id='rightAlignPref'>
<div id=fixed>
<div>
<button id="button1">BURGER</button>
<button id="button2">HOTDOG</button>
</div>
</div>
</div>
</div>
</div>
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var preference = document.getElementById("preference");
var foodpic = document.getElementById("foodpiclocation");
var foodpic;
button1.addEventListener('click', function() {
foodpicurl = 'burger.svg';
});
button2.addEventListener('click', function() {
foodpicurl = 'hotdog.svg';
});
preference.addEventListener('click', function() {
var foodpic = document.createElement('img');
foodpic.src = foodpicurl;
foodpiclocation.innerHTML = '';
foodpiclocation.appendChild(foodpic);
});

Clean solution using vanilla Javascript. NOTE: I suggest you add this to your HTML code <div id="foodpicloc"><img id="foodpic"></div> in your HTML first. Changing the image's src is quicker and cleaner than appending a new image element everytime the image changes.
Define
function mapClickToImage(imageSelector, updateBtnSelector, btnSectorToImageSrcMapping) {
var currentImageSrc = null;
var imageElement = document.querySelector(imageSelector);
for (var btnSelector in btnSectorToImageSrcMapping) {
var buttonElement = document.querySelector(btnSelector);
buttonElement.addEventListener('click', function() {
currentImageSrc = btnSectorToImageSrcMapping[btnSelector];
});
var updateButtonElement = document.querySelector(updateBtnSelector);
updateButtonElement.addEventListener('click', function() {
if (currentImageSrc) {
imageElement.src = currentImageSrc;
}
});
}
Usage
mapClickToImage('#foodpic', '#preference', {
'#button1': 'burger.svg',
'#button2': 'hotdog.svg'
});

Related

When I append an element it does it twice rather than once

I am trying to make multiple comment boxes for a website. The first click to create the text area and submit button works fine. However when I click another it appends the text area and submit button twice - creating two text areas and submit buttons and then three and so on..
If you go to https://alexpd93.github.io/FAC-Website/ and click on various comment buttons it should make more sense.
I would like it so that each time I click on the comment button, it only creates one text area for each section.
How can I fix this?
function addComment(element) {
const boxContainer = element.parentNode.parentNode.parentNode;
const commentContainer = element.parentNode;
commentContainer.classList.add("comment-container-after-click");
const commentBox = document.createElement("textarea");
commentBox.classList.add("comment-box-after-click");
commentBox.placeholder = "What are your thoughts?";
commentBox.innerHTML = "";
const submitComment = document.createElement("button");
submitComment.classList.add("submit-comment-after-click");
submitComment.innerHTML = "Comment";
commentContainer.append(commentBox, submitComment);
submitComment.onclick = function submitComment() {
let comment = commentBox.value;
const newComments = document.createElement("p");
boxContainer.appendChild(newComments);
newComments.innerHTML = `${comment}`;
commentBox.value = "";
};
}
function comment(event) {
const commentButton = event.target;
commentButton.style.display = "none";
const commentIcon = document.getElementsByClassName("comment-icon");
const iconArray = Array.from(commentIcon);
iconArray.forEach((icon) => {
if (icon.nextElementSibling.style.display === "none") {
icon.style.display = "none";
addComment(commentButton);
}
});
}
<div class="comments-container" id="comments">
<img id="commentIcon" class="comment-icon" src="Images/Comment.png" alt="comment icon">
<button class="comment-button" id="commentButton" onclick="comment(event)" > Comment </button>
</div>
After playing around with the website I believe I understood the problem. You are calling addComment() for all elements with class comment-icon. And due to your (tbh) little bit weird handling of addComment() this adds a comment to every single one of this elements.
I've corrected the error below and marked my changes with comments.
function addComment(element) {
const boxContainer = element.parentNode.parentNode.parentNode;
const commentContainer = element.parentNode;
commentContainer.classList.add("comment-container-after-click");
const commentBox = document.createElement("textarea");
commentBox.classList.add("comment-box-after-click");
commentBox.placeholder = "What are your thoughts?";
commentBox.innerHTML = "";
const submitComment = document.createElement("button");
submitComment.classList.add("submit-comment-after-click");
submitComment.innerHTML = "Comment";
commentContainer.append(commentBox, submitComment);
submitComment.onclick = function submitComment() {
let comment = commentBox.value;
const newComments = document.createElement("p");
// why append to the box container? Then all comments from different textareas will be merged
// boxContainer.appendChild(newComments);
commentContainer.appendChild(newComments);
newComments.innerHTML = `${comment}`;
commentBox.value = "";
};
}
function comment(event) {
const commentButton = event.target;
commentButton.style.display = "none";
const commentIcon = document.getElementsByClassName("comment-icon");
// add the comment once not to every comment box available
addComment(commentButton);
const iconArray = Array.from(commentIcon);
iconArray.forEach((icon) => {
if (icon.nextElementSibling.style.display === "none") {
icon.style.display = "none";
// this causes that the comment is added multiple times
// addComment(commentButton);
}
});
}
<div div="all-comments">
<div class="comments-container" id="comments">
<img id="commentIcon" class="comment-icon" src="https://dummyimage.com/100x100/000/fff" alt="comment icon">
<button class="comment-button" id="commentButton" onclick="comment(event)"> Comment </button>
</div>
<div class="comments-container" id="comments">
<img id="commentIcon" class="comment-icon" src="https://dummyimage.com/100x100/000/fff" alt="comment icon">
<button class="comment-button" id="commentButton" onclick="comment(event)"> Comment </button>
</div>
<div class="comments-container" id="comments">
<img id="commentIcon" class="comment-icon" src="https://dummyimage.com/100x100/000/fff" alt="comment icon">
<button class="comment-button" id="commentButton" onclick="comment(event)"> Comment </button>
</div>
</div>

how to load div in one file from another (inside iframe)

My goal is to load data from the appropriate file into div sections when I select any option.
I need to load <div> in one file from another (inside iframe). I'm stuck on how to get value and store it in variable. Everything works fine if I assign to variables (template_1, template_2, template_3) any static data but I want to load it from another files (template_one.html, template_2.html and so on).
template_1 has load() method but I know that this is wrong. Instead I want a path to appropriate file div. Same with other variables
I found a similar solution here with function load but I'm not sure if this will work and how add this to my function.
Array objects are random so please don't worry about it
jQuery(document).ready(function($) {
var template_1 = $('#section_one').load('template_one.html', '.section_one')
var template_2 = "<div><h1>template2</h1></div>"
var template_3 = "<div><h1>template3</h1></div>"
var templates_array = [
[template_1, template_1, template_1, template_1, template_1],
[template_2, template_2, template_2, template_2, template_2],
[template_3, template_3, template_3, template_3, template_3],
]
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
document.getElementById('id_template').onchange = function(event) {
let get_val = event.target.selectedOptions[0].getAttribute("value");
if (get_val) {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = templates_array[get_val - 1][i];
};
} else {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = '';
};
};
};
});
project tree
Jquery Code
$(document).ready(function(){
$(document).on('click', '#button_1', function() {
$('#div_1').load('one.html')
});
$(document).on('click', '#button_2', function() {
$('#div_2').load('two.html')
})
});
HTML Code
Button_1
<BR>
<BR>
Button_2
<BR>
<BR>
<div id="div_1"></div>
<div id="div_2"></div>
I hope this one help you.
In the iframe:
<textarea id="ta"></textarea>
<script>
$(document).ready(function(){
$(document).on('change', '#ta', function() {
parent.textAreaChanged(this.value);
});
});
</script>
In the parent:
<div id="display"></div>
<script>
function textAreaChanged(value){
$('#display').text(value);
}
</script>

Insert Image to div upon click

I want to be able to add an image to this div once the button is clicked and a check box is checked. I have already confirmed that the checkbox portion works properly, but can't get the photo to go into the div.
Here is what I currently have:
<button id="show_button">Show System</button>
<div class="box" id="AC1"></div>
<script>
var show_button = document.getElementById('show_button');
var show = function() {
// AC Relevant Components;
var ch_mGT = document.getElementById('mGT').checked;
// Set AC1
if (ch_mGT) {
var AC1_html = "<img src='http://localhost/....png' alt='Micro Turbine'
height='50px'>";
document.getElementById("AC1").innerHTML(AC1_html);
}
}
show_button.addEventListener("click",show);
</script>
I also have already tried:
var AC1_img = document.createElement("img");
AC1_img.src = 'http://localhost/....png'
document.getElementById('AC1').appendChild(AC1_img);
You said you tried using appendElement, but it seems to be working in the below example.
var show_button = document.getElementById('show_button');
var show = function() {
var ch_mGT = document.getElementById('mGT').checked;
var AC1_img = document.createElement('img')
AC1_img.src="https://i.ytimg.com/vi/r4Hve6fZ7ik/maxresdefault.jpg"
AC1_img.style.height = "50px"
AC1_img.alt = 'Micro Turbine'
if (ch_mGT) {
document.getElementById("AC1").appendChild(AC1_img)
}
}
show_button.addEventListener("click",show);
<div class="box" id="AC1"></div>
<input type="checkbox" id="mGT">
<button id="show_button">Show System</button>

How to assigned different url link when a particular button from groups of button is selected?

I want to create a group of buttons that when clicked will return different download link to the user email. I am trying to do it with javascript switch but I not sure how to return the download link so that the download link can be retrieved using PHP get to send in the email.
<div class="row">
<div class="col-md-3">
<div class="text-center">
<i class="fa fa-file" style="font-size:48px; color:#00ffff;"></i>
<span><h6>User Manual:Accounting</h6></span>
<button class="downloadButton" id="401" type="button" data-toggle="modal" data-target="#downloadModal" style="border-radius:5px; outline:none; background-color:Transparent;">
<i class="fa fa-download" style="font-size:24px; color:#737373;"></i>
</button>
</div>
</div>
<script>
function linkFunction(){
var buttonClass = document.getElementsByClassName["download-button"];
var buttonId = buttonId.attr('id');
var link;
Is this maybe what you're looking for? Hope it helps!
<html>
<head>
<script>
window.onload = doThis;
/* This one would work well and allow you to pass arguments */
function doThis() {
var buttonClass = document.getElementById("download_button");
var buttonId = buttonClass.id;
var buttonName = buttonClass.name;
var buttonLinkId = buttonClass.getAttribute('data-linkId');
buttonClass.addEventListener('click', buttonClickedCaller);
function buttonClickedCaller(){
buttonClicked(buttonLinkId);
}
function buttonClicked(foo) {
console.log('http://localhost/?' + foo);
window.location = 'http://localhost/?' + foo;
// window.open('http://localhost/?'+foo);
}
}
/*
// here's a simpler example
function doThis() {
var buttonClass = document.getElementById("download_button");
var buttonId = buttonClass.id;
var buttonName = buttonClass.name;
var buttonLinkId = buttonClass.getAttribute('data-linkId');
buttonClass.addEventListener('click', buttonClicked);
function buttonClicked() {
console.log('http://' + buttonLinkId);
}
}
// careful though, this won't work.
function doThis() {
var buttonClass = document.getElementById("download_button");
var buttonId = buttonClass.id;
var buttonName = buttonClass.name;
var buttonLinkId = buttonClass.getAttribute('data-linkId');
// Passing a Variable in Below Here
buttonClass.addEventListener('click', buttonClicked(buttonLinkId));
// Will Break Here & It's executed onload, but the above one isn't
function buttonClicked(foo) {
console.log('http://' + foo);
}
}
*/
</script>
</head>
<body>
<div class="row">
<div class="col-md-3">
<div class="text-center">
<span><h6>User Manual:Accounting</h6></span>
<button id="download_button" data-linkId="401">
Click Here
</button>
</div>
</div>
</body>
<html>

Can't insert a div into another internal div

I need your help to solve a problem I have.
I have this code:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="aaa()"/>
</div>
</div>
I want to use insert into the internal div (id=edit1) another new div I generated.
I tried alike code but it's not running:
js:
function aaa()
{
var elem = createDivLine();
var el1 = document.getElementById("div1");
var el2 = el1.getElementById("edit1");
el2.appendChild(elem);
}
function createDivLine()
{
var tempDiv1 = document.createElement("div");
tempDiv1.innerHTML = "Sam";
return tempDiv1;
}
The result should looks like this:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="createDivTable()"/>
<div>"Sam"</div>
</div>
</div>
JSFiddle: http://jsfiddle.net/KknXF/
Since IDs are unique, it is not valid to attempt to get an element's children by ID.
Remove this line:
var el1 = document.getElementById('div1');
And change the following line to:
var el2 = document.getElementById('edit1');
In the event that you have some irrepairably (I can never spell that word...) broken HTML that you can't possibly change, try this:
var el2 = document.querySelector("#div1 #edit1");
It should be
function aaa() {
var elem = createDivLine();
var el2 = document.getElementById("edit1");
el2.appendChild(elem);
}
Demo: Fiddle

Categories