Unable to add content using insertAdjacentHTML after i have successfully removed it - javascript

this is my code:
"use strict";
const searchBox = document.querySelector("#myText");
const searchBtn = document.querySelector(".btn-search");
const searchContainer = document.querySelector(".search-container");
let mainText = document.querySelector(".main-text");
const quit = document.querySelector("#btn-close");
let showMain;
const newMain = "";
let printMain = function(text) {
showMain = `
<article class="country">
<h1>Country you Searched</h1>
<p>Hello</p>
<p>${text}</p>
</article>`;
console.log(`Our show main is : ${showMain}`);
mainText.insertAdjacentHTML("beforeend", showMain);
};
searchBox.addEventListener("click", function() {
if (searchBox.value === "Type in") {
searchBox.value = "";
}
});
searchBtn.addEventListener("click", function() {
if (searchBox.value && searchBox.value !== "Type in") {
console.log(searchBox.value);
printMain(searchBox.value);
searchBox.value = "";
} else {
alert("please type in country name!");
}
});
quit.addEventListener("click", function() {
//mainText.remove(showMain);
const myDiv = document.getElementById("myId");
const parent = myDiv.parentNode;
parent.removeChild(myDiv);
console.log(showMain);
});
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script defer src="script.js"></script>
<title>Simple Work</title>
<button id="btn-close">go back</button>
</header>
<body>
<main class="container">
<div class="main-text" id="myId"></div>
<p class="search-container">
<label>Type In : </label>
<input type="text" id="myText" value="Type in" />
</p>
<button class="btn-search">input</button>
</main>
</body>
</html>
So, I was trying to make code that add the text using insertAdjacentHTML
and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML.
I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?
(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)

When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.
You should probably only remove the element with classname of country:
document.querySelector('.country').remove();

Related

How do i add edit buttons next to contacts in my contact list?

I specifically got an account on here to ask about this code where I've been sitting for a good while without finding a solution.
I'm new with coding and I am making a contacts list in Javascript where I so far have managed to make the list, but now I want to add buttons on the side of each contact, one where I can edit the contact and another where I can delete it. But I can't manage to create a button input through my js code.
Specifically for how I want the edit button to work is to change the attribute of the contacts name/number from readonly to where you can write and change it. Also, if there are any other improvements I could make to the rest of my code please let me know!
HTML:
<!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">
<title>contacs list</title>
</head>
<h1>Your contacts</h1>
<hr>
<section>
<form id="getForm">
<label>Name:</label>
<input
placeholder = " Bertil..."
type="text"
id="contactName">
<label>phone:</label>
<input
placeholder = "xxx-xxx-xx-xx"
type="text"
id="contactNumber">
<input
type="submit"
class="saveButton"
onclick="getContact()">
</form>
</section>
<section>
<h3>My contacts</h3>
<div>
<ul id="contactsList">
</ul>
</div>
</section>
Javascript:
var contactList = [];
var getContact = function(){
event.preventDefault();
var newContact = {
name: document.getElementById("contactName").value,
number: document.getElementById("contactNumber").value
}
contactList.push(newContact);
console.log(contactList)
printList();
}
var printList = function (){
var li = document.createElement("li");
li.innerText = " ";
var list = document.getElementById("contactsList");
for (var i = 0; i < contactList.length; i++) {
li.innerText = contactList[i].name + " " + contactList[i].number + " ";
list.appendChild(li);
}
}
Thanks!
I have tried a bunch of things but none work so I think they're irrelevant?

Replace HTML Tag and it's content with JS

I don't know quite anything about JS so i need your help. I've just searched on internet but i didn't found anything about what i will ask you. I need to change an html tag and all it's content and i think that the best way to do this could be JS. For example:
I need that the tag
<p id="usernameText">My Username</p>
will be changed with this
<input type="text" name="uname" id="uname" placeholder="Inserire qui l\'username" style="width:100%">
with the click of an item so i think that i should use onclick="myfunction()", but i don't have any idea where to start with the JS code! There's someone who can help me please?
<!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" />
<title>Document</title>
</head>
<body>
<div id="div1">
<p id="toggleItem">My Username</p>
<button onclick="onClick()">Toggle</button>
</div>
<script>
const onClick = () => {
const div1 = document.getElementById("div1");
const toggleItem = document.querySelector("#toggleItem");
if (toggleItem.tagName === "INPUT") {
const p = document.createElement("p");
p.innerText = "Username";
p.id = "toggleItem";
div1.appendChild(p);
} else {
const input = document.createElement("input");
input.name = "uname";
input.placeholder = "Username";
input.type = "text";
input.id = "toggleItem";
div1.appendChild(input);
}
toggleItem.remove();
};
</script>
</body>
</html>
I've found an easyest way, i have multiple elements to change so ive added also some var
function edit(id, type, name, placeholder){
var element = document.getElementById(id);
var final = document.createElement('td');
final.innerHTML = '<input type="'+type+'" name="'+name+'" id="'+name+'"
placeholder="Inserire qui '+placeholder+'" style="width:100%">';
element.parentNode.replaceChild(final, element);
}
and in html i've made like this:
<td id="indirizzoText">
<p>Address<i class="fas fa-pen" onClick="edit('indirizzoText', 'text', 'indirizzo', 'l\'indirizzo')"></i>
</p>
</td>
I've used a wrong way?

My EDIT button is not working properly? (Javascript Todo List) Beginner

I am a beginner in Javascript and is currently trying to make a todo list web app. But currently stucked at the edit button.
As you can see, I wanted to make an editable checklist but somehow everytime I hit the edit button, a new input comes out instead of replacing the current one. It also removes the 'checkbox' somehow.
Can anyone tell me where I did wrong? Thank you for your time!
Somehow the edit button doesn't work at all when I try to run it on VSCode. Here it works, but not as I wanted though.
const ul = document.querySelector('#invitedList');
ul.addEventListener('click', (event) => {
if(event.target.tagName === 'BUTTON') {
const button = event.target;
const li = button.parentNode;
if(button.textContent === 'edit') {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
} else if(button.textContent === 'save') {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
}
});
<!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">
<title>Document</title>
<script src="test.js"></script>
</head>
<body>
<!-- TASK LIST THAT IS SUPPOSED TO BE EDITABLE GOES DOWN HERE, AS A TEMPLATE -->
<div id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>
Have you considered trying Node.ReplaceChild() instead of creating a new element? Not sure how to tell you exactly how to do it but here is a link to the documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
I'd suggest to change styling instead of creating and removing elements. Here is possible solution:
let isEditState = false;
const editButton = document.querySelector('#editbtn');
editButton.addEventListener('click', (event) => {
const span = document.querySelector('#editable');
const checkbox = document.querySelector('#checkbox');
const text = document.querySelector('#text');
if (isEditState) {
span.innerText = text.value;
checkbox.style.display = 'inline';
text.style.display = 'none';
editButton.innerText = 'edit';
} else {
checkbox.style.display = 'none';
text.style.display = 'inline';
editButton.innerText = 'save';
}
isEditState = !isEditState;
});
<!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">
<title>Document</title>
</head>
<body>
<div id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox" id="checkbox"/>
<input type="text" id="text" style="display: none"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>

I can't figure out how to append a user's input into an array in Javascript

I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>

Scan to elementbyid on button click?

This example prompts for barcode scan, and then places the value into "scan-input" box. This works great for ONE input/ONE button.
My issue is i want to be able to add multiple inputs/buttons, and have the scan then place the value in the corresponding input text box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'/>
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN
</button>
</div>
<script>
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, { engineLocation: engineLocation });
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
const scanInput = document.getElementById("scan-input");
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>#scan:after {display:none;}</style>
</html>`
I want to be able to add multiple buttons/inputs. and have the corresponding button place it into the scan-input spot.
`<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN</button>
<input id="scan-input2" type="text" placeholder="Scan Receiver #2...">
<button id="scan2" onclick="scan()">SCAN</button>`
[text1] [button1] ----- scan places value into text1
[text2] [button2] ----- scan places value into text2
Here's a slightly adapted version of your HTML (using a digit in every id will help us keep things simpler):
<input type="text" id="scan-input1" />
<button type="button" id="scan1">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2">SCAN</button>
Then, in our JavaScript, we can use the following function to send a message to scan-input1 if scan1 is pressed, scan-input2 if scan-2 is pressed, and so on:
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
document.getElementById(`scan-input${num}`).value = "Scan Complete";
});
});
The code above:
Adds a click event listener to every button,
Gets the number from the id of whichever button is clicked,
Uses that number to target the correct input.
The advantage of the solution above is that it scales automatically. As long as you follow the same naming convention for each id (scan3, scan-input3, etc.), every a new button and input will have identical behaviour.
Edit: Your Code
Below, I've inserted my suggestion into your code - only changing the bare minimum:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input type="text" id="scan-input1" />
<button type="button" id="scan1" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input3" />
<button type="button" id="scan3" placeholder="Scan Receiver...">SCAN</button>
</button>
</div>
<script>
let scanInput;
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
scanInput = document.getElementById(`scan-input${num}`);
scan();
});
});
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, {
engineLocation: engineLocation
});
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>
#scan:after {
display: none;
}
</style>
</html>`

Categories