I have a dynamic HTML table created using json data. I want to create an extra column for datapicker plugin. My requirement is that when I click on a particular datapicker cell for the corresponding row, an input field should be created in that cell. When this input is clicked, the datapicker for this particular row should be invoked. I should be able to pick-up the date of my choice from the inline calender(this functionality is provided by the datapicker).In my case this date pick-up is not happening, rather this error is appearing:
Uncaught Missing instance data for this datepicker
This is the jsfiddle link to the code:
https://jsfiddle.net/0akqg9b8/3/
<html>
<head>
<meta content="text/javascript; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://code.jquery.com/jquery-1.11.1.min.js" integrity="sha256-VAvG3sHdS5LqTT+5A/aeq/bZGa/Uj04xKxY8KM/w9EE=" crossorigin="anonymous"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.11.1.min.js" integrity="sha256-VAvG3sHdS5LqTT+5A/aeq/bZGa/Uj04xKxY8KM/w9EE=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
</head>
<body>
<div id="container">
<p class="message box"></p>
</div>
<style>
#myelement {
width: 80%;
margin: auto;
border: 0.06em solid #999;
border-spacing: 0.3em;
box-shadow: 0.7em 0.7em 0.7em #999;
background: #a1deee;
}
#myelement tr{
color: blue;
}
#myelement td {
width: 10%;
padding: 0.5em;
border: 0.1em solid #000;
font-size: 15px;
text-align: center;
cursor: pointer;
}
button {
width: 10%;
padding: 0.5em;
border: 0.1em solid #000;
font-size: 15px;
text-align: center;
cursor: pointer;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<script>
var keys;
var myValue;
var myVar;
var myTableRows = [];
var html;
var table;
var c;
var myRow;
var myCol;
json = [{
ShipperID: 1,
CompanyName: "Federal Package",
Phone: "(503) 555-9931"
},
{
ShipperID: 2,
CompanyName: "United Package",
Phone: "(503) 655-7865"
},
{
ShipperID: 3,
CompanyName: "My Package",
Phone: "(508) 955-8997"
}
];
getMyData();
function getMyData() {
let myData = json[0];
let myTablehead = [];
myTablehead.push(myData);
html = '';
for (let i = 0; i < json.length; i++) {
myTableRows.push(json[i])
}
myTablehead.forEach(function(val) {
keys = Object.keys(val);
//html table starts here
html += "<table class='myTable' id=\"myelement\">"
html += "<tr>";
keys.forEach(function(key) {
html += "<th>" + key + "</th>";
});
html += "";
html += "</tr>";
});
myTableRows.forEach(function(val) {
mykeys = Object.keys(val);
//Set up the html row
html += "<tbody id=\"myRows\">"
html += "<tr class=\"thisRow\">"
for (var mykeys in val) {
myValue = val[mykeys];
html += "<td class='normalBtn'>"
html += myValue;
html += "</td>";
}
html += "<td class=\"dateBtn\">"
html += "Enter Date:";
html += "<input type = \"text\" class='datepicker-1'>"
html += "</td>";
html += "</tr>";
});
html += "</tbody>"
html += "</table>";
document.getElementsByClassName('message')[0].innerHTML += html;
}
$(".dateBtn").on('click','input',function(){
$("input").remove('.datepicker-1');
})
$.fn.timeline = function() {
return this.click(function(){
var myinput = "<input type = \"text\" class='datepicker-1' val=''></input>";
$(this).append(myinput);
var dataInstance = $( ".datepicker-1" ).datepicker();
$("input:text").val(function(n){
return dataInstance;
});
})
}
$(".dateBtn" ).timeline();
</script>
</body>
</html>
I did some changes in the code, because there was a lot of not really needed part.
var keys;
var myValue;
var myVar;
var myTableRows = [];
var c;
var myRow;
var myCol;
json = [{
ShipperID: 1,
CompanyName: "Federal Package",
Phone: "(503) 555-9931"
},
{
ShipperID: 2,
CompanyName: "United Package",
Phone: "(503) 655-7865"
},
{
ShipperID: 3,
CompanyName: "My Package",
Phone: "(508) 955-8997"
}
];
getMyData();
function generateDateInput() {
let input = $('<input>').attr({'type': 'text', 'class': 'datepicker-1'});
input.datepicker();
input.on('focus', function() {
// The datepopup activates by the focus, not by the click.
// So let's remove every input which is not in focus.
$('.myTable input:not(:focus())').remove();
}).on('click', function(event) {
// This needed to stop bubbling effect down to the tr.
event.stopPropagation();
});
return input;
}
function getMyData() {
let myData = json[0];
let myTablehead = [];
myTablehead.push(myData);
let table = '';
for (let i = 0; i < json.length; i++) {
myTableRows.push(json[i])
}
myTablehead.forEach(function(val) {
keys = Object.keys(val);
//html table starts here
table = $('<table>', document).attr({'class': 'myTable', 'id': 'myelement'});
let tr = $('<tr>');
keys.forEach(function(key) {
tr.append($("<th>").text(key));
});
table.append(tr);
});
let tbody = $('<tbody>').attr('id', 'myRows');
myTableRows.forEach(function(val) {
mykeys = Object.keys(val);
//Set up the html row
let tr = $('<tr>').attr('class', 'thisRow');
for (var mykeys in val) {
tr.append(
$('<td>').attr('class', 'normalBtn').text(val[mykeys])
);
}
tr.append(
$('<td>').attr('class', 'dateBtn').text('Enter Date:').append(generateDateInput())
).on('click', function() {
$('td:eq(3)', this).append(generateDateInput());
// After append we set the focus to the input field from the current row. This
// will only work in the current form until there's only one input field.
$('input', this).focus();
});
tbody.append(tr);
});
table.append(tbody);
$('#container').append(table);
}
#myelement {
width: 80%;
margin: auto;
border: 0.06em solid #999;
border-spacing: 0.3em;
box-shadow: 0.7em 0.7em 0.7em #999;
background: #a1deee;
}
#myelement td {
width: 10%;
padding: 0.5em;
border: 0.1em solid #000;
font-size: 15px;
text-align: center;
cursor: pointer;
}
button {
width: 10%;
padding: 0.5em;
border: 0.1em solid #000;
font-size: 15px;
text-align: center;
cursor: pointer;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
<html>
<head>
<meta content="text/javascript; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://code.jquery.com/jquery-1.11.1.min.js" integrity="sha256-VAvG3sHdS5LqTT+5A/aeq/bZGa/Uj04xKxY8KM/w9EE=" crossorigin="anonymous"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.11.1.min.js" integrity="sha256-VAvG3sHdS5LqTT+5A/aeq/bZGa/Uj04xKxY8KM/w9EE=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js"></script>
</head>
<body>
<div id="container">
<p class="message box"></p>
</div>
</body>
</html>
Related
I'm trying to figure out how to make a dialogue system that shows the text and after you click it removes all the text in the box and new text appears in its place. (I want to be able to do this multiple times)
var container = document.querySelector(".text");
var speeds = {
pause: 400,
slow: 120,
normal: 50,
fast: 20,
superFast: 10
};
var textLines = [{
speed: speeds.slow,
string: "this is a test"
},
{
speed: speeds.pause,
string: "",
pause: true
},
{
speed: speeds.normal,
string: "pls help me"
},
{
speed: speeds.fast,
string: "idk what im doing",
classes: ["red"]
},
{
speed: speeds.normal,
string: ":("
}
];
var characters = [];
textLines.forEach((line, index) => {
if (index < textLines.length - 1) {
line.string += " ";
}
line.string.split("").forEach((character) => {
var span = document.createElement("span");
span.textContent = character;
container.appendChild(span);
characters.push({
span: span,
isSpace: character === " " && !line.pause,
delayAfter: line.speed,
classes: line.classes || []
});
});
});
function revealOneCharacter(list) {
var next = list.splice(0, 1)[0];
next.span.classList.add("revealed");
next.classes.forEach((c) => {
next.span.classList.add(c);
});
var delay = next.isSpace && !next.pause ? 0 : next.delayAfter;
if (list.length > 0) {
setTimeout(function() {
revealOneCharacter(list);
}, delay);
}
}
setTimeout(() => {
revealOneCharacter(characters);
}, 600)
const btn = document.getElementById('btn');
html,
body {
height: 100%;
width: 100%;
}
.text span {
opacity: 0;
}
.text span.revealed {
opacity: 1;
}
.text span.green {
color: #27ae60;
}
.text span.red {
color: #ff0000;
}
body {
background: #3498db;
padding: 3em;
font-family: 'Sora', monospace;
}
.text {
font-size: 6vw;
word-spacing: 0.2em;
margin: 0 auto;
background: #fff;
padding: 1em;
border-bottom: 1vw solid #0e6dad;
position: relative;
line-height: 1.2em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="text">
</div>
<button id="textchanger"> continue </button>
<script src="script.js">
}
</script>
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
</body>
</html>
so far all I'm able to make from this is a single phrase appear on the screen and that's about it. to change it, I have to go in manually.
I make (almost) all the js from scratch because it would have been really hard to refactor your code in order to achieve what you want, what I've done seems to work, it is pretty straightforward :
const container = document.querySelector(".text");
const btn = document.querySelector("#textchanger");
// rename speeds in delays which is more coherant
const delays = {
slow: 120,
normal: 50,
fast: 20,
superFast: 10
};
const textLines = [
{
delay: delays.slow,
string: "this is a test"
},
{
delay: delays.normal,
string: "pls help me"
},
{
delay: delays.fast,
string: "idk what im doing",
classes: ["red"]
},
{
delay: delays.normal,
string: ":("
}
];
const revealLine = (lineIndex = 0) => {
const line = textLines[lineIndex]
let charIndex = 0
const nextChar = () => {
const char = line.string[charIndex]
const span = document.createElement('span')
span.textContent = char
span.classList.add(...(line.classes ?? []))
container.appendChild(span)
charIndex++
if (charIndex < line.string.length)
setTimeout(nextChar, line.delay);
else if (lineIndex + 1 < textLines.length) {
const cb = () => {
// remove this listener to display the next one
btn.removeEventListener('click', cb)
// clear the container
Array.from(container.children).forEach(el => el.remove())
// reveal the next line
revealLine(lineIndex + 1)
}
btn.addEventListener('click', cb)
}
}
nextChar()
}
revealLine()
html,
body {
height: 100%;
width: 100%;
}
.text span.green {
color: #27ae60;
}
.text span.red {
color: #ff0000;
}
body {
background: #3498db;
padding: 3em;
font-family: 'Sora', monospace;
}
.text {
font-size: 6vw;
word-spacing: 0.2em;
margin: 0 auto;
background: #fff;
padding: 1em;
border-bottom: 1vw solid #0e6dad;
position: relative;
line-height: 1.2em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div class="text">
</div>
<button id="textchanger"> continue </button>
</body>
</html>
I am pretty new to js, and I am building a color scheme generator as a solo project.
I am now stuck on select the html element that created from dynamically.
I tried to select both label and input element below, using document.getElementByClassName but it gives me 'undefined'
I wanna select both label and input elements and add an click eventListner so that they can copy the result color code from that elements.
<label for='${resultColor}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor}' type="text" value='${resultColor}'/>`
const colorPickerModes = [ 'monochrome', 'monochrome-dark', 'monochrome-light', 'analogic', 'complement', 'analogic-complement', 'triad quad']
const colorPickerForm = document.getElementById("colorPick-form");
const colorPickerInput = document.getElementById("colorPicker");
const colorPickerModeDropDown = document.getElementById("colorPick-mode");
const resultColorDiv = document.getElementById("result-color-div");
const resultColorCodeDiv = document.getElementById("result-code-div");
let colorPicked = "";
let modePicked = "";
let resultColorDivHtml =''
let resultCodeDivHtml=''
let colorSchemeSetStrings = [];
let resultColorSchemeSet = [];
fetchToRender()
renderDropDownList();
//listen when user change the color input and save that data in global variable
colorPickerInput.addEventListener(
"change",
(event) => {
//to remove # from the color hex code data we got from the user
colorPicked = event.target.value.slice(1, 7);
},
false
);
//listen when user change the scheme mode dropdownlist value and save that data in global variable
colorPickerModeDropDown.addEventListener('change', (event)=>{
modePicked =
colorPickerModeDropDown.options[colorPickerModeDropDown.selectedIndex].text;
})
//whe user click submit btn get data from user's input
colorPickerForm.addEventListener("submit", (event) => {
event.preventDefault();
// To get options in dropdown list
modePicked =
colorPickerModeDropDown.options[colorPickerModeDropDown.selectedIndex].text;
fetchToRender()
});
//when first load, and when user request a new set of color scheme
function fetchToRender(){
if (!colorPicked) {
//initialize the color and mode value if user is not selected anything
colorPicked = colorPickerInput.value.slice(1, 7);
modePicked = colorPickerModes[0]
}
fetch(
`https://www.thecolorapi.com/scheme?hex=${colorPicked}&mode=${modePicked}`
)
.then((res) => res.json())
.then((data) => {
let colorSchemeSetArray = data.colors;
for (let i = 0; i < 5; i++) {
colorSchemeSetStrings.push(colorSchemeSetArray[i]);
}
// to store each object's hex value
for (let i = 0; i < colorSchemeSetStrings.length; i++) {
resultColorSchemeSet.push(colorSchemeSetStrings[i].hex.value);
}
renderColor();
colorSchemeSetStrings = []
resultColorSchemeSet = [];
});
}
function renderColor(){
//to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet.map((resultColorItem) => {
return `<div class="result-color"
style="background-color: ${resultColorItem};"></div>`;
}).join('')
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor}' class='copy-label'>
Click to copy!</label>
<input class='result-code' id='${resultColor}'
type="text" value='${resultColor}'/>`;
})
.join("");
resultColorDiv.innerHTML = resultColorDivHtml;
resultColorCodeDiv.innerHTML = resultCodeDivHtml;
}
function renderDropDownList() {
const colorPickerModeOptionsHtml = colorPickerModes
.map((colorPickerMode) => {
return `<option class='colorSchemeOptions' value="#">${colorPickerMode}</option>`;
})
.join("");
colorPickerModeDropDown.innerHTML = colorPickerModeOptionsHtml;
}
* {
box-sizing: border-box;
}
body {
font-size: 1.1rem;
font-family: "Ubuntu", sans-serif;
text-align: center;
margin: 0;
}
/*------Layout------*/
#container {
margin: 0 auto;
width: 80%;
}
#form-div {
width: 100%;
height:10vh;
margin: 0 auto;
}
#colorPick-form {
display: flex;
width: 100%;
height:6vh;
justify-content: space-between;
}
#colorPick-form > * {
margin: 1rem;
height: inherit;
border: 1px lightgray solid;
font-family: "Ubuntu", sans-serif;
}
#colorPick-form > #colorPicker {
width: 14%;
height: inherit;
}
#colorPick-form > #colorPick-mode {
width: 45%;
padding-left: 0.5rem;
}
#colorPick-form > #btn-getNewScheme {
width: 26%;
}
#main {
display: flex;
flex-direction:column;
width:100%;
margin: .8em auto 0;
height: 75vh;
border:lightgray 1px solid;
}
#result-color-div {
width:100%;
height:90%;
display:flex;
}
#result-color-div > *{
width:calc(100%/5);
}
#result-code-div {
width:100%;
height:10%;
display:flex;
}
.copy-label{
width:10%;
display:flex;
padding:0.5em;
font-size:0.8rem;
align-items: center;
cursor: pointer;
background-color: #4CAF50;
color: white;
}
#result-code-div .result-code{
width:calc(90%/5);
text-align: center;
border:none;
cursor: pointer;
}
.result-code:hover, .result-code:focus, .copy-label:hover, .copy-label:focus{
font-weight:700;
}
/*------Button------*/
#btn-getNewScheme {
background-image: linear-gradient(
to right,
#614385 0%,
#516395 51%,
#614385 100%
);
}
#btn-getNewScheme {
padding:0.8rem 1.5rem;
transition: 0.5s;
font-weight: 700;
background-size: 200% auto;
color: white;
box-shadow: 0 0 20px #eee;
border-radius: 5px;
display: block;
cursor: pointer;
}
#btn-getNewScheme:hover,
#btn-getNewScheme:focus {
background-position: right center; /* change the direction of the change here */
color: #fff;
text-decoration: none;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="index.css">
<title>Color Scheme Generator</title>
</head>
<body>
<div id="container">
<div>
<header><h1 class="site-title">🦎 Color Scheme Generator 🦎</h1></header>
</div>
<div id="form-div">
<form id="colorPick-form" method="get" >
<input id="colorPicker" type="color" />
<select name="colorPick-mode" id="colorPick-mode">
</select>
<button type='submit' id="btn-getNewScheme">Get Color Scheme</button>
</form>
</div>
<div id="main">
<div id="result-color-div">
</div>
<div id="result-code-div">
</div>
</div>
<script src="index.js" type="module"></script>
</body>
</html>
I think the problem is rendering timing. So you need to add event listener below the code where set innerHTML.
function renderColor() {
// to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet
.map((resultColorItem) => {
return `<div class="result-color" style="background-color: ${resultColorItem};"></div>`;
})
.join("");
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor}' type="text" value='${resultColor}'/>
`;
})
.join("");
resultColorDiv.innerHTML = resultColorDivHtml;
resultColorCodeDiv.innerHTML = resultCodeDivHtml;
// here! add event listener
const labels = document.getElementsByClassName("result-code");
Object.entries(labels).forEach(([key, label]) => {
label.addEventListener("click", (event) =>
alert(`copy color: ${event.target.value}`)
);
});
}
const resultColorCodeDiv=document.getElementById("resultColorCodeDiv")
const resultColorDiv=document.getElementById("resultColorDiv")
resultColorSchemeSet=[
{color:"red", code: "#ff0000"},
{color:"green", code: "#00ff00"},
{color:"blue", code: "#0000ff"}]
function renderColor(){
//to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet.map((resultColorItem) => {
return `<div class="result-color" style="background-color: ${resultColorItem.color};"></div>`
}).join('')
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor.code}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor.code}' type="text" value='${resultColor.code}'/>`
})
.join("")
resultColorDiv.innerHTML = resultColorDivHtml
resultColorCodeDiv.innerHTML = resultCodeDivHtml
addListener(document.querySelectorAll(".result-color"))
addListener(document.querySelectorAll(".result-code"))
}
renderColor()
function addListener(elements){
for(const element of elements){
element.addEventListener("click" , ()=>{
// add copy logic here
console.log("hello")
})
}
}
<body>
<div id="resultColorDiv"></div>
<div id="resultColorCodeDiv"></div>
</body>
I have written this code to get the squares of a grid to change their background color to black upon a mouseover event. It works when the page initially loads, but if I create a new grid the mouseover event no longer works.
I updated the original post with a snippet. Sorry I didn't do that from the beginning.
let number = 16;
makeGrid(number);
function makeGrid(number) {
for (let i=0; i < number; i++) {
for (let j=0; j < number; j++) {
const rows = document.createElement('div');
const container = document.getElementById('container')
rows.setAttribute('class', 'rows');
container.appendChild(rows);
}
}
container.style.gridTemplateColumns = `repeat(${number}, 1fr)`;
container.style.gridTemplateRows = `repeat(${number}, 1fr)`;
}
//create new grid with on button
let newGrid = document.getElementById('newGrid');
newGrid.addEventListener('click', () => {
let number = prompt('Enter a number');
let container = document.getElementById('container');
container.textContent = '';
makeGrid(number);
})
//change background color to black
let changeClass = document.querySelectorAll('.rows');
changeClass.forEach((item) => {
item.addEventListener('mouseover', e => {
item.style.backgroundColor = 'black';
})
})
body {
background-color: rgb(5, 51, 5) ;
}
#container {
margin: auto;
width: 500px;
height: 500px;
display: grid;
border-style: solid;
border-width: thin;
border-color: lightslategray;
background-color: white;
}
.rows{
}
.black { background-color: black;
}
#header {
text-align: center;
}
#button {
text-align: center;
}
#footer {
text-align: center;
}
#newGrid {
background-color: lightgray;
color: darkcyan;
font-size: 20px;
padding: 12px 28px;
border-radius: 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id='header'>Etch-a-Sketch</h1>
<br>
<div id='button'>
<button id='newGrid' class='button'>New Grid</button>
</div>
<br>
<br>
<div id='container'></div>
<br>
<footer id='footer'>Made by: Joe Maniaci</footer>
<script src="main.js"></script>
</body>
</html>
When you query the DOM with document.querySelectorAll('.rows') and add the event listeners, there is only one "grid" in the DOM at that time. When a "grid" is subsequently added to the DOM, as triggered by the user's click event, you must instantiate event listeners on the newly added DOM nodes too.
A way to avoid this problem and a better approach overall in your situation is to use delegated event listeners. For example:
document.addEventListener('mouseover', e=>{
if(e.target.matches(‘.myClickableItemClass’){
e.target.style.backgroundColor = 'black';
}
}
Learn more about event delegation here: https://medium.com/#bretdoucette/part-4-what-is-event-delegation-in-javascript-f5c8c0de2983
I have my html and javascript code as below.
<!DOCTYPE html>
<html>
<head>
<style>
#demo {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
</style>
<style>
#demo1 {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
</style>
<div id ="demo"></div>
<div id ="demo1"></div>
<script>
var arr_args = [["ab", "cd"], ["ef", "gh"]];
var j, x = "";
for (i=0; i<2; i++) {
for (j=0; j< 2; j++) {
x = x + arr_args[i][j] + "<br />";
}
if(i == 0) {
document.getElementById("demo").innerHTML = x;
x="";
}
if(i==1) {
document.getElementById("demo1").innerHTML = x;
}
}
</script>
</html>
now instead of me creating demo and demo1 id's. I need the code t do it dynamically. Any help would be appreciated.
You can use backticks as below to get the id as dynamic
document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x;
var arr_args = [
["ab", "cd"],
["ef", "gh"]
];
var j, x = "";
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
x = x + arr_args[i][j] + "<br />";
}
document.getElementById(`demo${i == 0 ? '': i }`).innerHTML = x;
if (i == 0) {
x = "";
}
}
#demo1 {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
#demo {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
<div id="demo"></div>
<div id="demo1"></div>
You can use querySelectorAll to select all divs starting with "demo", then use the corresponding index to update.
var arr_args = [
["ab", "cd"],
["ef", "gh"]
];
var j, x = "";
//Get all divs with an ID starting with demo
var divs = document.querySelectorAll("[id^=demo]");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
x = x + arr_args[i][j] + "<br />";
}
//Update the corresponding div
divs[i].innerHTML = x;
if (i == 0) {
x = "";
}
}
#demo1 {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
#demo {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
<div id="demo"></div>
<div id="demo1"></div>
You probably really want to use a CSS class. .className in JavaScript.
//<![CDATA[
/* js/external.js */
var doc, html, bod, nav, mobile, M, I, S, Q, special, unspecial; // for use on other loads
addEventListener('load', function(){
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator;
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
special = function(str){
return str.replace(/&/g, '&').replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
unspecial = function(str){
return str.replace(/&/g, '&').replace(/'/g, "'").replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
var out = I('output'), arr = [['ab', 'cd'], ['ef', 'gh'], ['ij', 'kl', 'mn', 'op'], ['qr', 'st'], ['uv', 'wx', 'yz']], outerDiv, innerDiv;
arr.forEach(function(a){
outerDiv = M('div'); outerDiv.className = 'demo';
a.forEach(function(v){
// no need for `special` in this case but you may have special characters to escape
innerDiv = M('div'); innerDiv.innerHTML = special(v); outerDiv.appendChild(innerDiv);
});
output.appendChild(outerDiv);
});
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box;
}
.demo{
border: 1px solid green; padding: 10px; margin: 20px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='output'></div>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<style>
[id^="demo"] {
border: 1px solid green;
padding: 10px;
margin: 20px;
}
</style>
<div id="section"></div>
<script>
var arr_args = [["ab", "cd"], ["ef", "gh"], ["ij", "kl"]];
arr_args.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("section").innerHTML += "<div id=demo" + index + ">" + item[0] + "<br>" + item[1] + "<div>";
}
</script>
</html>
I am facing small problem here. here it comes all the output. But if I delete those it will delete from database also. I want to close the content only from html page rather deleting it from database.
I am using javascript of that. Any help will be greatly helpful for me.
HTML
<html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css">-->
<!-- <link rel="stylesheet" href="css/styles.css">-->
<!--
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-latest.js"></script>
<style>
/* my CSS here */
</style>
</head>
<body bgcolor="#45a049">
<div>
<form id=post-form>
<label for="fname">First Name :</label>
<input type="text" id="post-fname" name="firstname"><br>
<label for="lname">Last Name :</label>
<input type="text" id="post-lname" name="lastname"><br>
<label for="image">Select Image :</label>
<input type="file" id="post-image" ><br>
<input type="submit" value="Submit">
</form>
</div>
<list id="list-posts" style="list-style-type:circle; width:50%" border="2" cellspacing="1" cellpadding="100" >
</list>
<script type="text/javascript">
/* my JS here */
</script>
</body>
</html>
CSS
input[type=text],
select {
width: 50%;
/*align-content:center;*/
align-self: center;
padding: 5px 20px;
margin: 30px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=file],
select {
/*padding: 20px 5px;*/
padding-right: -5px;
padding-left: 50px;
margin: 20px 10px;
}
input[type=submit] {
width: 40%;
/*align-self: center;*/
background-color: #4CAF50;
color: white;
padding: 7px 30px;
/*align:center;*/
margin: 20px 10px;
margin-left: 5px;
margin-right: 5px;
text-align: center;
border: none;
border-radius: 10px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 10px;
background-color: #f2f2f2;
background-position: center;
background-size: contain;
/*background-position: 30px 60px;*/
position: absolute;
padding: 10px 10px;
margin: 80px 500px;
text-align: center;
align-self: center;
left=50%;
top=50%;
}
JS
Parse.initialize("", "");
var Post = Parse.Object.extend("UpdateDelete");
$("#post-form").submit(function(event) {
event.preventDefault();
var Firstname = $("#post-fname").val();
var Lastname = $("#post-lname").val();
var Image = $("#post-image").val();
var new_post = new Post;
new_post.set("Firstname", Firstname);
new_post.set("Lastname", Lastname);
var fileElement = $("#post-image")[0];
var filePath = $("#post-image").val();
var fileName = filePath.split("\\").pop();
console.log("sumbit for post clicked");
if (fileElement.files.length > 0) {
var file = fileElement.files[0];
var newFile = new Parse.File(fileName, file);
newFile.save({
success: function() {
console.log("Inserted");
},
error: function(file, error) {
console.log("Error");
}
}).then(function(theFile) {
new_post.set("Image", theFile);
new_post.save({
success: function() {
console.log("Image Saved");
},
error: function(error) {
console.log("Post Save with file error " + error.message);
}
});
});
} else {
new_post.save(Firstname, Lastname, {
success: function(new_post) {
console.log("All posted");
getPosts();
},
error: function(new_post, error) {
console.log("Error" + error.message);
}
});
}
});
// deleting item form list
$("#list-posts").on("click", "#delitem", function() {
close();
var id = $(this).attr("href");
console.log("ID retrieved" + id);
var query = new Parse.Query(Post);
var delobj = id;
query.equalTo("objectId", id);
query.get(delobj, {
success: function(delobj) {
delobj.destroy({});
location.reload();
console.log("Object deleted successfully");
},
error: function(delobj, error) {
console.log("error deleting");
}
});
});
function showDialog() {
$("#list-posts").on("click", "#showDialog()", function(e) {
e.preventDefault();
var x = document.getElementById("myDialog");
function showDialog() {
x.show();
}
})
}
// Retrieving
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results) {
console.log("Retrieving");
var output = "";
for (var i in results) {
var Firstname = results[i].get("Firstname");
var Lastname = results[i].get("Lastname");
var id = results[i].id;
// console.log(results[i].get("file"));
var img = "";
if (results[i].get("Image")) {
var file = results[i].get("Image");
var url = file.url();
console.log("url:" + url);
img = "<img src='" + url + "' style='width:170px;height:170px; margin:20px 10px'/>";
}
output += "<li style= 'list-style-type:circle' reversed='reversed' >";
output += "<h3 id='Firstname' href='" + id + "'>" + Firstname + "</h3>";
output += "<li style= 'list-style-type:circle' reversed='reversed' >";
output += "<h3 id='Lastname' href='" + id + "' >" + Lastname + "</h3>";
output += img;
output += "<button id='delitem' href='" + id + "' style='display:inline-block; margin:20px 10px'>delete</button>";
output += "<button id='mydialog' style='display:inline-block; margin:20px 10px'>User Info</button>";
output += "<dialog id='myDialog'> This is dialog window</dialog>";
output += "<button id='modals_close' style='display:inline-block; margin:20px 10px'>Close Info</button>";
output += "</li>";
$("#list-posts").html(output);
};
},
error: function(error) {
console.log("Query Error" + error.message);
}
});
}
getPosts();
First of all: you iterate through a list of items and create HTML for every item. This HTML contains DOM elements having ID. So a single ID occurs multiple times in your HTML, which it isn't allowed. Use classes instead.
There aren't the same amount of closing <LI> tags as opening ones.
I created a fiddle from your supplied code: https://jsfiddle.net/1muc0460/
But since accessing api.parse.com is unauthorized (due to initialize fails, because we need an app-key and a js-id), we can't get pretty far with it.
There are a lot errors in it. Selectors containing special character. There are Function definitions inside function definitions with the same name. Those add event handlers, but are never called (initialized).
I started some fixing: https://jsfiddle.net/1muc0460/1/
But I gave up. I don't know what logic you were trying to go after, so it's pretty hard to repair.
I added a test item as your JS would create, but none of your buttons had any effect.
As soon as you provide proper functional code, I can update this answer.