The code doesn’t have any error, but doesn’t work. I fill both inputs and click the button but it doesn’t print out the words.
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = listItem.textContent;
let myTodoTime = timeInputValue.textContent;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime;
myTodoInfo = getInputValue.value;
}
<div class="myApp border border-info">
<p class="text-center appTittle">To Do List</p>
<div class="todoThings" id="todo">
<ul>
<li id="todoListItem"></li>
</ul>
</div>
<div class="row mx-auto">
<p class="mr-3 ml-3 appTaskText">Task</p><input type="text" class="appInput" id="task">
<p class="mr-1 ml-3 appTaskText">Time</p><input type="number" id="timeInput" min="1" max="24">
</div>
<button type="submit" class="btn btn-info btn-sm addButton" id="add" onclick="addTask()">Add task</button>
<p id="errorMsg" class="text-danger mt-1 mb-1"></p>
</div>
This is not the full solution, However, i have corrected the variables to fix the basic issue of not showing the task. You should get some help with this solution and extend it.
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = getInputValue.value;
let myTodoTime = timeInputValue.value;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime;
myTodoInfo = getInputValue.value;
listItem.innerHTML = myTodoInfo;
}
<div class="myApp border border-info">
<p class="text-center appTittle">To Do List</p>
<div class="todoThings" id="todo">
<ul>
<li id="todoListItem"></li>
</ul>
</div>
<div class="row mx-auto">
<p class="mr-3 ml-3 appTaskText">Task</p><input type="text" class="appInput" id="task">
<p class="mr-1 ml-3 appTaskText">Time</p><input type="number" id="timeInput" min="1" max="24">
</div>
<button type="submit" class="btn btn-info btn-sm addButton" id="add" onclick="addTask()">Add task</button>
<p id="errorMsg" class="text-danger mt-1 mb-1"></p>
</div>
I fixed my issue this is the fix
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = getInputValue.value;
let myTodoTime = timeInputValue.value;
let myTodoInfo = myTodoInput + ' at ' + myTodoTime + 'PM';
listItem.textContent = myTodoInfo;
}
let myTodoInput = listItem.textContent;
let myTodoTime = timeInputValue.textContent;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime; // line isn't of value as it is overwritten below
myTodoInfo = getInputValue.value; // overwrites declaration.`
You are not printing anyway. No console.log() or alert() and no DOM injection.
Related
I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.
Can anyone please help me, I don't understand why the elements from the list are not showing.
var taskList = [];
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
button.onclick = function(){
var nHTML = '';
var userEnteredText = input.value;
taskList.push(userEnteredText);
taskList.forEach(function(task){
nHTML += '<li>'+task+'</li>';
});
document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
I tried checking several times but nothing is updating in the HTML document
You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];
button.onclick = function(){
let e = document.createElement('li');
e.innerHTML = input.value
tlist.appendChild(e)
// Optionally, clear the input field to prevent double adding the same task
input.value = '';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).
Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.
var taskList = [];
var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');
buttonAdd.addEventListener('click', (event)=>{
addTask(input.value);
});
buttonClear.addEventListener('click', (event)=>{
tasksList = [];
document.querySelector('#tasksList ul').remove();
});
function addTask(value){
if(taskList.length == 0){
document.getElementById('tasksList').append( document.createElement('ul') );
}
taskList.push(value);
const newLI = document.createElement('li');
newLI.innerText = value;
document.querySelector('#tasksList ul').append(newLI);
}
<body>
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="tasksList">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button id="clearInput" type="button" class="button">Clear All</button>
</div>
</div>
</body>
you just needed to use an ID on the tasklist.
getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:
document.getElementsByClassName('taskLists')[0].innerHTML
That said, here is a full version using recommended eventListener and IDs where relevant.
let tasks = [];
const taskList = document.getElementById('taskLists')
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');
const showTasks = () => {
taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};
add.addEventListener('click', () => {
var userEnteredText = input.value;
tasks.push(userEnteredText);
showTasks();
});
clear.addEventListener('click', () => {
tasks = [];
showTasks();
});
taskList.addEventListener('click', (e) => {
const tgt = e.target.closest('li');
if (!tgt) return; // not a task
const task = tgt.textContent;
tgt.remove()
tasks = tasks.filter(currentTask => currentTask != task); // remove from list
showTasks()
});
showTasks(); //init
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="taskLists"></div>
<div class="footer">
<span> You have <span id="pendingTasks"></span> left </span>
<button type="button" id="clear">Clear All</button>
</div>
</div>
I want to create a chat system (which i already accomplished), but a working username selector, and it gets the username in the input, then when the user sends a message via chat, it is their username!! And also, i tried putting it in a localStorage, so when the user refreshes or rejoins, the name is still there and not removed! I think im close, but it says UNDEFINED, which really got me confused? Please help? Thanks!!
localStorage.playerusername = document.querySelector(".hud-name").value;
let username = localStorage.playerusername;
let chatMsg = [];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" + currentUserName + ": </strong>" + chatMessage;
document.querySelector(".chat").appendChild(chatElem);
}
for (let i = 0; i < chatMsg.length; i++) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
sendMessage: function(messageContent) {
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
document.querySelector(".enterT").innerHTML = ""
},
addChatTopRemoverPackage: async function() {
if (chatMsg.length == 7) {
let chatElem = document.querySelector(".chat")
if (chatElem.children[0]) {
chatElem.removeChild(chatElem.children[0])
if (chatMsg.length > 0) {
chatMsg.shift()
//if (chatMsg.length == 0) {
//chatMsg.pop();
//}
}
}
}
},
chatRemoverRefresher: setInterval(() => {
Game.currentGame.variables.addChatTopRemoverPackage()
}, 0.000000000001)
}
}
}
HTML:
<div class="hud-name-select
type-text
maxlength-16
">
<input class="hud-name" type="text" maxlength="16" placeholder="Enter Nickname...">
<div></div>
<div><br></div>
<button class="btn-play btn-green background-color-green">
<div style="
display: none;
" display="none">Loading......<div></div>
</div>
<span>Play</span>
</button>
</div>
</div>
</div>
<div class="msgcont">
<div class="messages">
<h1>
CHAT
</h1>
<div class="chat">
</div>
<div>
<input class="enterT" type="text" placeholder="Enter A Message..!"><button
onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
</div>
<br>
</div>
</div>
Kevin
I don't know javascript but I want to use, search on my site. I found a good example on stackoverflow link
I joined all the parts and received the following code:
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
Everything works fine, but I need to search by class = 'code'. My question is:
How do I search for Qwr Tyu and <p class="dsh185">Code: <span class="code">5678</span></p> ? What did I try?
I duplicated javascript function code and changed the class from target to code, but nothing was received, now the search goes after the first function in the input.
I added a new function to the input SearchCode();;
In <span>5678</span> I added class="code"
And as I said above I dubbed javascript code and I changed 2 variables: from nodes to code new class name and from card to profilecard, only the new variable but the html tag remains the same.
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (code[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = "block";
} else {
profilecard[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
My question: How can I search the site after 2 html tags (Search by text in tags)?
Any idea how I can change the code, or where I went wrong etc ... Thanks
one idea can be to use innerText on parent tag profileCard
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (profilecard[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = 'block';
} else {
profilecard[i].style.display = 'none';
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
I have this code in html and javascript
HTML
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "You answered " + correct_ans + " correctly.";
if (answer_one === "abuja") {
correct_ans++;
}
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
my issue is that the correct_ans variable doesn't add when i type in the correct answer in the textbox
You should initialize the variable result after you check for the correct answer.
function getResult() {
let correct_ans = 0;
let answer_one = document.getElementById("question_one").value;
if (answer_one === "abuja") correct_ans++;
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
In your code, result was evaluated before the correct_ans increment.
Try this instead.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "";
if (answer_one === "abuja") {
correct_ans++;
}
result = You answered " + correct_ans + " correctly.
document.getElementById("result").innerHTML = result;
}
You declared the variable abuja before you updated the variable correct_ans. Put it after the if condition. If you'll add other questions you need to put the initial declaration of correct_ans = 0 out of the function or you're always going to get 0 or 1.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
if (answer_one === "abuja") {
correct_ans++;
}
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
I'm having an issue concatenating strings. Where I initially declare the 'output' variable in my last function, I'm able to get the number of questions correct printed to my modal window.
However, my concatenation of strings 2 lines down from that won't work and I've tried so many things. I'm sure it's something simple but any help would be appreciated!
I'm not sure how much code is relevant to the solution so I apologize for the wall of code.
I'm new to JS and my first post on Stackoverflow so any tips or advice is appreciated. Thanks in advance!
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = document.getElementById("quizResults").innerHTML = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script
(Disclaimer: This answer might not actually solve your problem, as noted in the comments. I can't delete it, though, because it was accepted.)
(Please see the other answer)
The line
var output = document.getElementById("quizResults").innerHTML = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
does not have the effect you think it does, because javascript does not interpret a statement like var a = b = c the way you think it does. Instead, it is better to use var a = c; var b = c;, like so:
var output = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
document.getElementById("quizResults").innerHTML = output;
For more information on how javascript interprets var a = b = c;, please see this question: Javascript a=b=c statements
The problem is that you're updating the output variable after you've already put it into the quizResults DIV. Assigning the string to .innerHTML makes a copy of it, it's not a reference to the variable, so updating the variable doesn't change the DIV contents. You need to assign to .innerHTML after you've performed the concatenation.
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
document.getElementById("quizResults").innerHTML = output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script