I Want the code to get the number the user has entered and display it on the screen. I know that its just a dumb mistake that I have made.
function run() {
const quest = document.getElementById('quest');
const data = quest.value;
const element = document.createElement('div').innerHTML = data
const store = document.getElementById('store');
store.appendChild(element)
}
body {
text-align: center;
}
<h1>Calucator</h1>
<input type="number" name="" id="quest">
<button onclick="run()">=</button>
<div id="store"></div>
As the comments in your question pointed - document.createElement('div').innerHTML = data is not a document node element
And use .textContent instead of .innerHTML - otherwise you'll introduce an XSS vulnerability.
function run() {
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
yourElement.textContent = data
const store = document.getElementById("store");
store.appendChild(yourElement);
}
What i changed in the function?
I first create the element, and then set it's text content. Finally i append it to the element you wanted.
Related
I have two textareas and I like to switch the content of these, so content of the first textarea shall be the content of the second textarea and vice versa. Following code just copy the content of the first textarea into the second, but the second step is not performed, so both textareas comprise the same content afterwards. No error occurs.
function switch_text_content(){
var src_text_memory = src_form.src_message.value;
var trgt_text_memory = trgt_form.trgt_message.value;
console.log(src_text_memory);
src_form.src_message.innerHTML = trgt_text_memory;
trgt_form.trgt_message.innerHTML = src_text_memory;
//switch_text_content2(trgt_text_memory);
}
You are doing in wrong way because you are using .innerHTML to set value instead you can to use .value property to set value of textarea. Like Below Example:
const switchBtn = document.querySelector('#switch-btn');
const firstTextarea = document.querySelector('#first-textarea');
const secondTextarea = document.querySelector('#second-textarea');
switchBtn.addEventListener('click', function() {
const firstContent = firstTextarea.value;
const secondContent = secondTextarea.value;
firstTextarea.value = secondContent;
secondTextarea.value = firstContent;
});
<textarea id="first-textarea">First Content</textarea>
<textarea id="second-textarea">Second Content</textarea>
<br/>
<button type="button" id="switch-btn">Switch</button>
I have some node list, and I am trying to get some values from this list.
It works fine but I can't append the values in new lines and everything rendered together.
<div class="newinsert"></div>
<script>
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML} `
indiv.append(html)
})
</script>
I tried adding <br> on html var but it just prints <br> with ""
\n doesn't work too
Thanks in advance.
EDIT: ok fixed it by
indiv.insertAdjacentHTML('beforeend', ${html} < br >)
append function receive string or HTMLNode element (more info)
but if your purpose is just to learn,you can simply replace InnerHtml content with your Html;
or concatenate it to the current content;
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML}<br> `
indiv.innerHTML = html
//or
indiv.innerHTML = indiv.innerHTML+html // if you effectly want to append conent to current dev content
})
<div class="newinsert"></div>
below i have JSON data for cafe menu and i want to view them in HTMl page as grid view showing image, name and price ... is there a way to do this in JS and HTML?
[
{
"placeImage": "assets/images/straw-1.jpg",
"placeName": " pizza",
"price": 15000
},
{
"placeImage": "assets/images/straw-1.jpg",
"placeName": " Burger",
"price": 15000
},
]
This partly depends on if you're processing that data on the server side or the client side. Either way, you can access the JSON data in your JS script like this:
const cafeData = require('./cafe.json'); // If it is in the same directory as the script
console.log(cafeData);
If you're trying to create a dynamic HTML page with data from a server, then try using a templating language like EJS, which is the simplest to learn for a JavaScript developer. If you're on the client side then you'll need to use the DOM to insert that data into your HTML. For example, if you have an element in a product card like this: <div id="pizzaPriceDisplay">
Then you're JS code might look something like this:
const priceDisplay = document.querySelector('#pizzaPriceDisplay');
pizzaPriceDisplay.innerText = '$' + cafeData[0].price;
Hope I helped and happy coding :)
Sure! Lets asume that your JSON data is stored in a javascript string
const jsonData = "..."; //The JSON string
The first thing to do would be to turn that json data into a javascript object that we can iterate. We can do that like this:
const data = JSON.parse(jsonData);
Cool, now, as far as i can tell you want to turn every item into an HTML element (like a card) and display all of them in a grid. The grid part can be pretty trivial now days using CSS Grid: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout.
So somewhere in your HTML you would want to have an element like this:
...
<div class="grid-container" id="menu-items-container">
<!-- We are going to insert your rendered data here -->
</div>
...
And somewhere in your css you will have something like this
...
.grid-container{
display:grid;
/* ... */
}
...
Now for the fun part. Taking your the contents of that data variable and turning them into html
//This function will take the data of one item
//And return an html element
function renderItem(item){
const base = document.createElement("div");
const img = document.createElement("img");
const title = document.createElement("h1");
const price = document.createElement("h2");
img.src = item.placeImage;
title.textContent = item.placeName;
price.textContent = item.price;
base.appendChild(img);
base.appendChild(title);
base.appendChild(price);
return base;
}
const container = document.querySelector("#menu-items-container");
for (let item of data){
container.appendChild(renderItem(item));
}
And that's about it, you'll probably want to style the inserted elements a little better, which you can do adding a few classes here and there. But you probably get the gist of it.
For the particular data you gave in the example this should produce something similar to this:
<div class="grid-container" id="menu-items-container">
<div>
<img src="assets/images/straw-1.jpg"/>
<h1>pizza</h1>
<h2>15000</h2>
</div>
<div>
<img src="assets/images/straw-1.jpg"/>
<h1>Burger</h1>
<h2>15000</h2>
</div>
</div>
Simply parse the JSON to JS object
let menu = JSON.parse('[{"placeImage": "assets/images/straw-1.jpg", "placeName": "Pizza", "price": 15000},{"placeImage": "assets/images/straw-1.jpg", "placeName": "Burger","price": 15000}]');
Then you can iterate over it using a loop and draw the HTML you want ex: Table
function drawMenu(menu) {
let tableElement = document.createElement("table");
// Draw the headers of the table
let headerTableRowElement = document.createElement("tr");
let imageHeaderElement = document.createElement("th");
imageHeaderElement.innerText = "Image";
headerTableRowElement.appendChild(imageHeaderElement);
let nameHeaderElement = document.createElement("th");
nameHeaderElement.innerText = "Name";
headerTableRowElement.appendChild(nameHeaderElement);
let priceHeaderElement = document.createElement("th");
priceHeaderElement.innerText = "Price";
headerTableRowElement.appendChild(priceHeaderElement);
tableElement.app.appendChild(headerTableRowElement);
// Draw the items in the menu
for (let i = 0; i < menu.length; ++i) {
let item = menu[i];
let menuItemTableRowElement = document.createElement("tr");
let imageElement = document.createElement("td");
let image = document.createElement("img");
image.setAttribute("src", item.placeImage);
imageElement.appendChild(image);
menuItemTableRowElement.appendChild(imageElement);
let nameElement = document.createElement("td");
nameElement.innerHTML = item.placeName;
menuItemTableRowElement.appendChild(nameElement);
let priceElement = document.createElement("td");
priceElement.innerHTML = item.price;
menuItemTableRowElement.appendChild(priceElement);
tableElement.appendChild(menuItemTableRowElement);
}
document.appendChild(tableElement);
}
Java Script
const cardDropdownTemplate = document.querySelector('[Card-Dropdown-Template]');
const cardDropdownContainer = document.querySelector('[card-dropdown-container]');
SearchBoxMainNav.addEventListener('input', async(event) =>{
var input = document.getElementById('SearchTerm').value;
const card = cardDropdownTemplate.content.cloneNode(true).children[0];
cardDropdownContainer.innerHTML = "";
if (input != "") {
var result = cardSearch(input);
console.log(result);
for (var i = 3; i > -1; i--) {
const name = card.querySelector("[Ygo-Card-Name]");
const desc = card.querySelector("[Ygo-Card-Desc]");
name.textContent = result[i].name;
desc.textContent = result[i].desc;
cardDropdownContainer.append(card);
}
console.log(card);
console.log(result);
}
})
Html
<div class="dropdown-Content" card-dropdown-container ></div>
<template Card-Dropdown-Template>
<div class="card-dropdown">
<div class="card-name" Ygo-Card-Name></div>
<div class="card-description" Ygo-Card-Desc></div>
</div>
</template>
So I have this code, when it executes it listens for an input then sends that input into my api searcher, it searches the api for the 4 most simmilar listings in name then Uses a dom template to create a box and puts all the information in it so i can make a Dropdown.
My problem is currently it is only creating one Box and is just overwriting the information in that one box instead of making multiple boxes. Am I just using append wrong or what? When i watch it in slow mo The data gets overwriitten even before the append is reached in the code, so maybe its just drawing the template in real time after the append and the append only makes a new box that first time then does nothing the rest of the times?
I have a code where I am trying to calculate a total value based on the value of the input selected by a user. It seems simple but I can't get the total to reflect. Please can someone show me where the fault is?
function calculate() {
var panel = parseInt(document.getElementsById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
}
document.getElementsById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate">Result</button>
<p id="total_hours">result displays here</p>
You need to
use for onclick="calculate()" take the function call, not only the function,
use getElementById, spelling matter,
declare all variables,
and finally move the output inside of the function
function calculate() {
var panel = parseInt(document.getElementById("panel").value),
panelv = 65,
panelt = panel * panelv,
derating_value = 2,
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
getElementById is singular
declare your vars
call calculate() with brackets
assign the value inside the function
</input> is not needed
Here is a version with eventListeners since other answers already showed you how to fix YOUR version
function calculate() {
var panel = +document.getElementById("panel").value;
if (panel === "" || isNaN(panel)) panel = 0;
let panelv = 65;
let panelt = panel * panelv;
let derating_value = 2;
document.getElementById("total_hours").textContent = (panelt * derating_value);
}
window.addEventListener("load", function() {
document.getElementById("calc").addEventListener("click", calculate)
calculate(); // run at load
})
<input type="number" id="panel" placeholder="panel quantity"><br>
<button type="button" id="calc">Result</button> result displays here: <span id="total_hours"></span>
First, you should call method calculate.
<button type="button" onclick="calculate()">Result</button>
Then, add this line document.getElementsById("total_hours").innerHTML = total_hours_standby; inside calculate function.
Alos, typo error: document.getElementById instead of document.getElementsById
There are couple of issues here:
Most you could have found out if you had looked into console logs.
For starter the function is called getElementById not getElementsById, because there is supposed to be only one element with unique id, so plural does not make sense here.
Another one is a logic error: not updating content after clicking on button i.e when calculate gets executed.
There is also one more syntax error, which is how functions should be passed to HTML element's attribute. It needs to be functionName() instead of functionName
This is how simply fixing this code could look like:
var total_hours_standby = 0;
function calculate() {
var panel = parseInt(document.getElementById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
document.getElementById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
Here I give you couple of ideas for improving it.
Since you use global variable total_hours_standby it may be a good
idea to encapsulate it. So called module pattern should do the job.
New value of total_hours_standby does not seem to depend on an old
one, so I guess you mean to use it somewhere else - in order to do
so, you need to expose it with "public" getter.
If above is not the case, then you don't need total_hours_standby
variable at all and you can just directly return it or display it
without storing this value in variable.
I put code for rendering in separate function - this is because rule
of thumb for functions is that they should have single
responsibility. One functions for calculations, another for rendering
and then one function for handling user's input and click event, that
uses two previous ones. This way if for example you only want to
calculate something without rendering result, then you just, simply can :)
I also stored DOM nodes in variables, instead of calling
getElementById, it is not due to performance, how it is often
assumed, I did it only for better readability.
Constants instead of hard-coded values.
var Calculator = (function() {
const panelInput = document.getElementById("panel");
const output = document.getElementById("total_hours");
const PANEL_V = 65;
const DERATING_VALUE = 2;
const render = value => output.innerHTML = value;
const calculate = value => value * PANEL_V * DERATING_VALUE;
let total_hours_standby = 0;
return {
handleInput: function() {
total_hours_standby = calculate(panelInput.value);
render(total_hours_standby);
},
getTotalHoursStandby: () => total_hours_standby
};
})();
<input type="number" id="panel" placeholder="Panel quantity" />
<button type="button" onclick="Calculator.handleInput()">Calculate</button>
<p id="total_hours">Result displays here</p>
It is typo,
document.getElementsById
should be
document.getElementById