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>
Related
How can i add multi lines together into different different span tag through this text box ?
There is an text box, by using this box i can insert a new div / span class content Right ?
But every time when i need to add new class i need to write a new line in this text box and need to press send button, Now i want that if i have 10 lines content together with "Enter" button line break
Like
My Line 1 is here
My Line 2 is here
My Line 3 is here
My Line 4 is here
My Line 5 is here
My Line 6 is here
My Line 7 is here
My Line 8 is here
... and so on
then i want to paste all 10 lines in this text box together and by pressing send button i want that all lines must be add in different different div / span class not all in one class with < br > tag that is working now.
so plz help me to improve my code
Love you Helper and Thanks in Advance
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
so plz help me to improve my code
Love you Helper and Thanks in Advance
I took some liberties and simplified your code as you can see below. It does everything I believe your code was attempting.
Note that I'm using .split("\n") to break your input based on each newline character and then iterate over that as necessary.
Also, you said you were inserting a div/span, but I don't see your code actually creating a span tag. I wrote my code to do that for you though.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
// split the textarea entries into an array
let lines = (textArea.value).split("\n");
// iterate over each line, creating a div/span and inserting into the DOM
lines.forEach( (line) => {
let encodedLine = encodeHtmlEntity(line);
let newElement = `<div class="me"><span>${encodedLine}</span></div>`;
innerDiv.innerHTML += newElement;
});
// reset the textarea
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
You can try using String.prototype.split() so that each text is separated by \n (new line) into an array, then you can iterate over each element like using Array.prototype.forEach(). Here's the code you can use:
sendButton.addEventListener('click', function () {
textArea.value.split('\n').forEach((text) => {
const message = new MessageContainerBuilder().BuildMessage(text);
innerDiv.appendChild(message);
});
textArea.value = '';
});
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'
});
I'm supposed to display an image after the user inserts its URL. It works fine on the first click, but instead of replacing the previous image with the new URL when the user input a new one, it just creates a new image below the previous.
That's my function so far:
HTML:
<p id="tt">Display an image using the image's URL</p>
<label>URL:
<textarea rows="1" cols="40" placeholder="Image URL" id="url"></textarea>
</label><br>
<label>Caption:
<textarea rows="1" cols="40" placeholder="Image caption" id="caption"></textarea>
</label><br>
<button id="btn">Add Image</button>
<br>
<div id="imgDiv"></div>
JS:
var getBtn = document.getElementById("btn");
getBtn.addEventListener('click', function() {
var figure = document.createElement("figure");
var image = document.createElement("IMG");
var figcaption = document.createElement("figcaption");
//attributing the input value in the first textarea as source for the image to be displayed
var url = document.getElementById("url").value;
image.src = url;
image.height = "200";
image.id = "newImage";
figure.appendChild(image);
//making the image a link to its url
var a = document.createElement("a");
a.href = url;
a.appendChild(image);
figure.appendChild(a);
//creating a Node and setting the input value from the second textarea as caption
var caption = document.getElementById("caption").value;
var text = document.createTextNode(caption);
document.getElementById("imgDiv").appendChild(figure);
figure.appendChild(figcaption);
figcaption.appendChild(text);
document.getElementById("menu").add(option);
//clear textarea after submitting url and caption
document.getElementById("url").value = "";
document.getElementById("caption").value = "";
});
EDIT - JSFiddle: https://jsfiddle.net/hpnLycer/4/
Can someone give me a hint how to solve this?
I tried understanding by reading "similar" questions, but I didn't find any that would solve my case.
Thank you anyway.
Hope this snippet will be useful
HTML
<input type ="text" id="imageIp" placeholder="New Image url"> <button id ="changeDisplay" > Change Display </button>
<div class ="demoDiv" id = "demoDiv">
</div>
CSS
.demoDiv{
margin-top:10px;
height:300px;
width:300px;
background-image: url("http://freebigpictures.com/wp-content/uploads/shady-forest.jpg");
JS
var getButton = document.getElementById("changeDisplay");
getButton.addEventListener('click',function(){
var getNewImage = document.getElementById("imageIp").value;
console.log(getNewImage);
document.getElementById("demoDiv").style.backgroundImage = "url('"+getNewImage+"')";
})
WORKING EXAMPLE
EDIT
In the latest snippet you have not defined these two arrays
imageArray
captionArray
You need to define them before you can push content in it.I have initialized that at the beginning but you can put them accordingly.But they must be initialized before you can put content in it.
var getBtn = document.getElementById("btn");
var imageArray = []; // Initializing imageArray
var captionArray=[]; // Initializing captionArray
getBtn.addEventListener('click', function() {
// rest of code
))
NOTE:Also in your snippet there is no HTML element with id menu,so when I run this code it thrown an error.
WORKING EXAMPLE WITH SUPPLIED CODE
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
I got a webpage with some homemade search engine which is supposed to look for some data in a server-side text file. I use JS to parse this file, it works well except for the very 1st time I use it... The culprit seems to be my fetchText() function which doesnt return anything the first time. Note that if I add a alert() inside the fetchText() it works correctly (see note in JS source code). I guess the IFRAME is not fully loaded or something. What can I do ?
Webpage code
<form style="margin-top:15px; margin-left:15px;width:200px;">
<input type="text" value="NGR_" id="srcTxtInput" style="margin-top:0px;margin-left:0px;width:100px;"/>
<input type="button" value="Go" onclick="SearchString('./Coordinates.txt')" />
</form>
<div id="searchResults" style="vertical-align:right;margin-top:25px;">
<select size="4" id="select_list" onchange="Selec_change();" ondblclick="Selec_change();" style="visibility: hidden; width:250px;margin-left:8px;" ></select>
<img id="closeImg" src="./close.png" height="15px" width="15px" style="opacity:0.5;visibility:hidden; margin-left:235px;margin-bottom:5px;margin-top:5px;vertical-align:top;" alt="Close results" title="Close results" onclick="HideSearch();" onmouseover="this.style.cursor='pointer';"/>
</div>
JS code
function SearchString(txtFile){
var slist = document.getElementById('select_list');
var str = trim(document.getElementById('srcTxtInput').value.toUpperCase());
if(str == "" ){
slist.options.length = 0; //empty list
HideSearch();
exit;
}
var txt = fetchText(txtFile);
//DO SOMETHING
}
function fetchText(txtFile) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.src = txtFile;
**//Note that if I add *alert(txtFrame.src)* here the function works the 1st time**
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
return text;
}
Since loading page content like that is an asynchronous operation, you can't expect the contents to be there immediately after setting the "src" attribute of your <iframe>. You'll have to put the code that searches through the text in a "load" event handler on the frame document.
That means you'll write something like:
fetchText(textFile, function(theText) {
// DO SOMETHING
});
and modify "fetchText()" to be more like this:
function fetchText(txtFile, whenLoaded) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.onload = function() {
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
whenLoaded(text);
};
txtFrame.src = txtFile;
}