Javascript function stops immediately - javascript

I have a function which enables the button 2(id keuze1) and button 3 ( id keuze 3) If i press button 1 (id = naam).
function init() {
let startKnop = document.getElementsByTagName("button")[0].addEventListener("click", startClicked, false);
}
function startClicked(event) {
let knop2 = document.getElementById("keuze1");
knop2.removeAttribute("disabled");
let knop3 = document.getElementById("keuze2");
knop3.removeAttribute("disabled");
toonVraag();
}
function toonVraag(event) {
let i = vraagTeller.value;
let vraag = document.getElementById('vraag');
vraag.innerHTML = "Hello World";
}
<label for="naam">Code: </label><input type="text" id="naam" />
</div>
<button disabled>Start</button>
<div>
<p id="vraag">Een vraag</p>
<button id="keuze1" disabled>Keuze1</button>
<button id="keuze2" disabled>Keuze2</button>
</div>
So it successfully runs the function startClicked(), but stops immediately.
If I add the code event.preventDefault() it doesn't go through to changing the text from my element(id = vraag).

Seems to work just fine, as exemplified in this JSFiddle
I did some clean-up though:
Removed the disabled attribute from the first button
Removed the </div> from the 2nd line
Added call to the init() function
As such:
function init() {
let startKnop = document.getElementsByTagName("button")[0].addEventListener("click", startClicked, false);
}
init();
function startClicked(event) {
let knop2 = document.getElementById("keuze1");
knop2.removeAttribute("disabled");
let knop3 = document.getElementById("keuze2");
knop3.removeAttribute("disabled");
toonVraag();
}
function toonVraag(event) {
let vraag = document.getElementById('vraag');
vraag.innerHTML = "Hello World";
}
<label for="naam">Code: </label><input type="text" id="naam" />
<button>Start</button>
<div>
<p id="vraag">Een vraag</p>
<button id="keuze1" disabled>Keuze1</button>
<button id="keuze2" disabled>Keuze2</button>
</div>

Related

why doesn't my local storage works but, copy of same code works

i got two copies of the same code with slight variation but seems the second one isnt working.
I have tried using ChatGPT to identify issues however, nothing was found. But as far as i can see, it should work.
But, everything i refresh, its removed.
I want the buttons to stay there.
working code:
const todoList = document.querySelector(".todo-list");
const todoForm = document.querySelector(".add-todo");
const removeList = document.querySelector(".remove-List");
let items = JSON.parse(localStorage.getItem("todoList")) || [
{
title: "Write on, 'do not forget to', and press '+' to add",
done: false,
},
{
title: "press 'X' to remove",
done: false,
},
{
title: "search via 'search box'",
done: false,
},
{
title: "filter via 'all'",
done: false,
},
];
function addTodo(e) {
e.preventDefault();
const title = this.querySelector("[name=item]").value;
const todo = {
title,
done: false,
};
items.push(todo);
saveTodos();
this.reset();
}
function createList(list = [], listTarget) {
listTarget.innerHTML = list
.map((item, i) => {
return `<li>
<input type="checkbox" id="todo${i}" data-index="${i}"
${item.done ? "checked" : ""} />
<label for="todo${i}">${item.title}
<span class="font-size:30px" data-index="${i}">X</span>
</label>
</li>`;
})
.join("");
}
function toggleDone(e) {
if (!e.target.matches("input")) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
saveTodos();
}
function removeSingle(e) {
if (!e.target.matches("span")) return;
const el = e.target;
const index = el.dataset.index;
items.splice(index, 1);
saveTodos();
if (items.length === 0) {
removeList.classList.add("hidden");
}
}
function saveTodos() {
localStorage.setItem("todoList", JSON.stringify(items));
createList(items, todoList);
showRemoveButton();
}
function removeData() {
items = [];
localStorage.removeItem("todoList");
createList(items, todoList);
removeList.classList.add("hidden");
}
function showRemoveButton() {
if (items.length > 1) return;
removeList.classList.remove("hidden");
}
todoList.addEventListener("click", toggleDone);
todoList.addEventListener("click", removeSingle);
todoForm.addEventListener("submit", addTodo);
removeList.addEventListener("click", removeData);
// Init list
createList(items, todoList);
<div class="ToDo-container">
<header class="app-header">
<div class="app-header1">
<div class="title">
<h1 class="app-title">ToDo List</h1>
</div>
<div class="select-button">
<select id="filter">
<option value="all">All</option>
<option value="completed">Completed</option>
<option value="incomplete">Incomplete</option>
</select>
</div>
</div>
<div class="search-header">
<input type="text" id="search" placeholder="Search Todos">
<button type="button" id="search-button" class="btn">Search</button>
</div>
</header>
<section class="app-body">
<div id="toDo">
<ul class="todo-list"></ul>
<form class="add-todo">
<input
type="text"
placeholder="Don't Forget to..."
name="item"
required
/>
<input type="submit" value="+" />
</form>
</div>
<button class="remove-List btn">Remove All</button>
</section>
</div>
// Add button function
function addButton() {
// Prompt for button link and name
var link = prompt("Enter the button link:");
var name = prompt("Enter the button name:");
// Create new button element
var newButton = document.createElement("button");
newButton.innerHTML = name;
newButton.setAttribute("onclick", "location.href='" + link + "'");
// Append new button to button container
document.getElementById("button-container").appendChild(newButton);
// Save buttons to local storage
saveButtons();
}
// Remove buttons function
function removeButtons() {
// Clear button container
document.getElementById("button-container").innerHTML = "";
// Save buttons to local storage
saveButtons();
}
// Save buttons to local storage
function saveButtons() {
// Get button container HTML
var buttonHTML = document.getElementById("button-container").innerHTML;
// Save button HTML to local storage
localStorage.setItem("buttons", buttonHTML);
}
// Load buttons from local storage on page load
window.onload = function () {
// Get button HTML from local storage
var buttonHTML = localStorage.getItem("buttons");
// Set button container HTML
document.getElementById("button-container").innerHTML = buttonHTML;
};
<div class="shortcuts-container">
<header class="shortcut-header">
<h1 class="shortcut-title">Quick Links</h1>
</header>
<section class="shortcut-body">
<form id="button-form">
<div id="button-container"></div>
<button type="button" onclick="addButton()">Add Button</button>
<button type="button" onclick="removeButtons()">Remove Buttons</button>
</form>
</section>
</div>
i want some help with identifying the bug in my code
As you have mentioned that your "second one" is not working, I have focused on the second piece of code. This peice of code adds a button for which we need to provide a link and name via alert box, which is technically supposed to be a hyperlink. I have added 2 buttons using that and refreshed page multiple times but the newly added buttons always stay. Local storage is working just fine.
Also, looking at your code, there is NO localStorage.removeItem() present. Hence the window.onload works fine. However, if you have any error logs in console of dev tools, please provide them for further debugging.
Also, if there is a way for you attach a video link of testing with dev tools console visible that would really help to understand why it doesn't work for you.

it seems that i only have one key in my localstorage and it keeps storing all the values into it(localstorage)

hey i am trying to make a phonebook where everytime i add someones name and phonenumber it displays it into the front page and then i can remove or edit...
now i have tried to add a remove function so it removes only the one row or name i choose after many tries i noticed in the application(in the inspect where the developers tools) there is only one key and it seems like i am storing all the arrays (values) into it , now what if i want to remove one value only from the key i am not sure if its possible
maybe i have to make it so i have multiple keys with each key with its own value i am not sure
this is my js code
"use strict";
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
} //end of function
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
} //end of function
cancelOverlay("cancelOverlay", "formContainer");
//
let phoneArray = [];
window.onload = init;
const submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", function addPerson() {
const person = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
};
if (person.name != "" && person.phoneNumber != "") {
phoneArray = JSON.parse(localStorage.getItem("person")) || [];
phoneArray.push(person);
localStorage.setItem("person", JSON.stringify(phoneArray));
phoneArray = localStorage.getItem("person");
phoneArray = JSON.parse(phoneArray);
window.location.reload(true);
} //end if
} //end addPerson)
);
function createLayout(person) {
const divv = document.getElementById("outPutContainer");
let row = document.createElement("ul");
row.innerHTML = `
<li>${person.name} </li>
<li>${person.phoneNumber} </li>
<button class="insideRemoveBtn"> - </button>
`;
divv.appendChild(row);
} //end of function
function getPersonArray() {
return JSON.parse(localStorage.getItem("person"));
} //end of function
function init() {
const personArray = getPersonArray();
for (let i = 0; i < personArray.length; i++) {
const person = personArray[i];
createLayout(person);
const insideRemoveBtn = document.querySelector(".insideRemoveBtn");
insideRemoveBtn.addEventListener("click", function removeSingleItem() {
localStorage.removeItem('person');
location.reload(true);
});
}
} //end of function
const removeAllBtn = document.getElementById("removeAllBtn");
removeAllBtn.addEventListener("click", function removeAll() {
localStorage.clear();
location.reload(true);
});
and this is my html code if needed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PhoneBook</title>
<link rel="stylesheet" href="Css/Whole.css">
<script defer src="JavaScript/PU.js"></script>
</head>
<body>
<h1>PhoneBook</h1>
<div class="childContainer">
<div class="buttonsContainer">
<div>
<input type="search" placeholder="search" class="searchBar"></div>
<div class="buttonsRightSide"> <button value="submit" id="addBtn" class="addBtn">+</button>
<button value="submit" id="removeAllBtn" class="removeAllBtn">-</button>
<button value="submit" id="saveBtn" class="saveBtn">*</button></div>
</div>
<div class="formContainer">
<form class="addForm" id="addForm">
<h2>Create Contact</h2>
<label for="name">First name*:</label>
<input id="name" type="text" pattern="[A-Z][a-zA-Z]{3,7}" required><br>
<label for="phoneNumber">Phone number*:</label>
<input id="phone" type="number" pattern="[0][5][0-8][ -]?\d{7}" required><br>
<label for="Adress">Address:</label>
<input type="text" id="Address"><br>
<label for="Email">Email:</label>
<input type="email" id="Email"><br>
<label for="Description">Description:</label>
<textarea type="text" id="Description"></textarea><br>
<div class="sendCancelButtons">
<button type="submit" class="submitButton" id="submitButton">Send</button>
<button value="submit" class="cancelOverlay">Cancel</button></div>
</form>
</div>
<div id="outPutContainer" class="outPutContainer">
</div>
</div>
</body>
</html>
any hints and suggestions are welcome and thanks in advance <3
From what I understood from your question, you are storing all your phonebook data inside person key. For deleting any specific "person" from the localStorage you can parse the array once again and then remove that "person" from array and save it back to localStorage. I'm assuming you want to remove person by it's phone number.
function removeByPhoneNumber(phoneNumber){
const prevArray = JSON.parse(localStorage.getItem("person")) || [];
const newArray = prevArray.filter(_person => _person.phoneNumber !== phoneNumber)
localStorage.setItem("person", JSON.stringify(newArray))
}

How to use removeChild method?

const toDoForm = document.querySelector(".todo__form"),
toDoInput = document.querySelector(".todo__input");
toDoList = document.querySelector("li");
let toDoArray = [];
function addToDoList() {
toDoForm.addEventListener('submit', event => {
toDoArray.push(toDoInput.value);
toDoList.innerHTML += `<ul>${toDoArray[toDoArray.length-1]}</ul>`;
event.preventDefault();
toDoInput.value = "";
});
}
function clearList() {
const toDoUl = document.querySelector("ul");
toDoForm.addEventListener('click', event => {
toDoArray = [];
toDoUl.parentNode.removeChild(toDoUl);
});
}
function init() {
addToDoList();
clearList();
}
init();
<h1>To-Do List</h1>
<div class="todo">
<form class="todo__form">
<input class="todo__input" type="text">
<input class="todo__submit" type="submit" value="Submit">
<input class="todo__clear" type="button" value="Clear">
</form>
</div>
<div class="todo-list">
<li></li>
</div>
I'm making a to-do list with javascript and i tried to use removeChild method to clear to-do list but when i run the code, it keeps getting an error like this -> Uncaught TypeError: Cannot read property 'parentNode' of null at HTMLFormElement. How can i solve it?
The query document.querySelector("ul"); is returning undefined because there is no ul element in the HTML. Try changing the div to ul tag
<ul class="todo-list">
<li></li>
</ul>
First, I thought you want remove one item at a time, then I made some changes which may be useful but you if you don't need it, you could remove delete function.
For adding an item, you enter a job name, for example 'Job1' an then press "Submit" button.
For deleting an item, you enter a job name, for example 'Job1' an then press "Delete" button.
Press 'Clear' to clear all items.
JavaScript:
<script>
let toDoArray = [];
let toDoForm;
window.onload = () => {
toDoForm = document.querySelector(".todo__form"),
toDoInput = document.querySelector(".todo__input");
toDoList = document.querySelector("ul");
clearButton = document.querySelector(".todo__clear");
deleteButton = document.querySelector(".todo__delete");
init();
};
function addToDoList() {
toDoForm.addEventListener('submit', event => {
toDoList.innerHTML += `<li>${toDoInput.value}</li>`;
event.preventDefault();
toDoInput.value = "";
});
}
function deleteItem() {
deleteButton.addEventListener('click', event => {
const toDoUl = document.querySelector("ul");
let allLi = document.querySelectorAll('li');
allLi.forEach(li => {
if (li.innerHTML === toDoInput.value)
toDoUl.removeChild(li);
});
toDoInput.value = "";
});
}
function clearList() {
clearButton.addEventListener('click', event => {
const toDoUl = document.querySelector("ul");
toDoUl.innerHTML = '';
});
}
function init() {
addToDoList();
deleteItem();
clearList();
}
</script>
HTML:
<body>
<h1>To-Do List</h1>
<div class="todo">
<form class="todo__form">
<input class="todo__input" type="text">
<input class="todo__submit" type="submit" value="Submit">
<input class="todo__delete" type="button" value="Delete">
<input class="todo__clear" type="button" value="Clear">
</form>
</div>
<div class="todo-list">
<ul></ul>
</div>
<script src="todo.js"></script>
</body>
First, you need to change <li></li> to <ul></ul>. You can get help from w3school link.
There is a StackOverflow answer about this issue Stackoverflow. You can check that.

how to display value of input in DIV object in real time

F.e I have div which id is someDiv and input text which id is someInput - and how to do that value of input object will display in DIV in real time? If i type letter "a" in input, it should automatically display in DIV.
Which function should I use?
I'm the real begginer in jQuery.
I find this code:
$(function() {
$('#someInput').keyup(function() {
$('#someDiv').text($(this).val());
});
});
Use input event
$(function() {
$('#someInput').on("input", function() {
$('#someDiv').text($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="someInput">
<div id="someDiv"></div>
<input id="realTimeInput" type="text"/>
<div id="someDiv">
</div>
<script>
$("#realTimeInput").on('change',function(){
$("#someDiv").text($("#realTimeInput").text());
}
</script>
you can check this code , when you keyup theb this value will show in content div so you can also input event like keypress, change etc
$('#someInput').keyup(function () {
$('#yourinput').show();
// var dev = $(this).val();
$('#yourinput').html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter Text :<input id="someInput" type="text"/>
<div id="yourinput" style="display: none;border: 1px solid #ccc;margin-top:10px;">
</div>
for more information
https://www.w3schools.com/jquery/event_keyup.asp
Vanilla Javascript Alternative:
Use the addEventListener() method to invoke a callback function when a specified event type occurs (e.g: keydown) on an EventTarget.
ES5:
var INPUT_EL = document.getElementById('UI_input'),
OUTPUT_EL = document.getElementById('UI_output');
function updateText() {
OUTPUT_EL.innerHTML = INPUT_EL.value;
}
INPUT_EL.addEventListener('keydown', updateText);
var INPUT_EL = document.getElementById('UI_input'),
OUTPUT_EL = document.getElementById('UI_output');
function updateText() {
OUTPUT_EL.innerHTML = INPUT_EL.value;
}
INPUT_EL.addEventListener('keydown', updateText);
<body>
<input type="text" id="UI_input" value="test value">
<div id="UI_output">this is sample</div>
</body>
ES6:
const INPUT_EL = document.getElementById('UI_input');
const OUTPUT_EL = document.getElementById('UI_output');
let updateText = () => OUTPUT_EL.innerHTML = INPUT_EL.value;
INPUT_EL.addEventListener('keydown', updateText);
const INPUT_EL = document.getElementById('UI_input');
const OUTPUT_EL = document.getElementById('UI_output');
let updateText = () => OUTPUT_EL.innerHTML = INPUT_EL.value;
INPUT_EL.addEventListener('keydown', updateText);
<body>
<input type="text" id="UI_input" value="test value">
<div id="UI_output">this is sample</div>
</body>

Output paragraph to web page depending on whether a user input answer is true or false

I want to make an application with 3 questions, each with 2 buttons: yes and no. I want to output a different paragraph in response, depending on whether the answer was true or false (not an alert message!). How do I proceed??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tegne med Javascript</title>
<script>
function oppstart () {
function hs(){
document.getElementById('utskrift').onclick = "riktig";
}
function hu(){
document.getElementById('utskrift').onclick = "feil";
}
function ss(){
document.getElementById('utskrift1').onclick = "riktig";
}
function su(){
document.getElementById('utskrift1').onclick = "feil";
}
function ts(){
document.getElementById('utskrift2').onclick = "riktig";
}
function tu(){
document.getElementById('utskrift2').onclick = "feil";
}
}
</script>
</head>
<body>
jeg har hode
<p id="utskrift"></p>
<button type="submit" id="hs">Sann</button> <button type="submit"
id="hu">USann</button>
<br>
<br>
<p id="utskrift1"></p>
jeg liker Skyrim <button type="submit" id="ss">Sann</button> <button
type="submit" id="su">USann</button>
<br>
<br>
<p id="utskrift2"></p>
jeg heter Tarzan <button type="submit" id="ts">Sann</button> <button
type="submit" id="tu">USann</button>
</body>
Each question's Yes/No buttons will have a click event callback function that will check the answer given and deliver the correct output.
Don't use submit buttons for this since you aren't actually submitting form data anywhere, regular button types will do.
This can be optimized a bit by combining the 3 functions I'm showing below into a single one, but that will complicate the code beyond beginner level, so you may want to stick with this approach for now.
// Get references to all of the buttons
var q1P = document.getElementById("utskrift1");
var q1Sann = document.getElementById("hs");
var q1Usann = document.getElementById("hu");
var q2P = document.getElementById("utskrift2");
var q2Sann = document.getElementById("ss");
var q2Usann = document.getElementById("su");
var q3P = document.getElementById("utskrift3");
var q3Sann = document.getElementById("ts");
var q3Usann = document.getElementById("tu");
// Set up each set of buttons to invoke a validation function when they are clicked
q1Sann.addEventListener("click", q1Validate);
q1Usann.addEventListener("click", q1Validate);
q2Sann.addEventListener("click", q2Validate);
q2Usann.addEventListener("click", q2Validate);
q3Sann.addEventListener("click", q3Validate);
q3Usann.addEventListener("click", q3Validate);
// Validation functions
function q1Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q1Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
// Update the paragraph with the message
q1P.textContent = message;
}
function q2Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q2Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
q2P.textContent = message;
}
function q3Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q3Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
q3P.textContent = message;
}
p { color: blue; }
<div>
jeg har hode
<button type="button" id="hs">Sann</button>
<button type="button" id="hu">USann</button>
<p id="utskrift1"></p>
</div>
<div>
jeg liker Skyrim
<button type="button" id="ss">Sann</button>
<button type="button" id="su">USann</button>
<p id="utskrift2"></p>
</div>
<div>
jeg heter Tarzan
<button type="button" id="ts">Sann</button>
<button type="button" id="tu">USann</button>
<p id="utskrift3"></p>
</div>

Categories

Resources