Hi im really new to javascript and stuck on a textbook exercise where I increase the increment of variable i by 1 to be able to continuing listing the inputs. Here is my code so far, can anyone guid me on what I am doing incorrect thank you
<body>
<header>
<h1>
Project 2 Test 1
</h1>
</header>
<article>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExp"></p>
</div>
<form>
<fieldset>
<label for="wishList" id="placeLabel">
Type the name of a wish list item, then click Submit:
</label>
<input type="text" id="wishList" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
i = 1;
listitem = "";
function processitems() {
if (i<= 5) {
listitem ="item" +i;
document.getElementById(listitem).innerHTML = document.getElementById("wishList").value;
document.getElementById("wishlist").value ="";
if (i===5) {
document.getElementById("resultsExp").innerHTML = "Your wish list has been submitted";
}
//inside the processitems() function of the main if statement, after the nested if statement, add a statement to increment the value of i by 1.
i =+1;
}
}
var btn = document.getElementById("button");
if (btn.addEventListener) {
btn.addEventListener("click", processitems, false);
} else if (btn.attachEvent) {
btn.attachEvent("onclick", processitems);
}
</script>
i =+1; is assigning 1 to i. You should be doing i += 1 instead:
<body>
<header>
<h1>
Project 2 Test 1
</h1>
</header>
<article>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExp"></p>
</div>
<form>
<fieldset>
<label for="wishList" id="placeLabel">
Type the name of a wish list item, then click Submit:
</label>
<input type="text" id="wishList" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
i = 1;
listitem = "";
function processitems() {
if (i <= 5) {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById("wishList").value;
document.getElementById("wishList").value = "";
if (i === 5) {
document.getElementById("resultsExp").innerHTML = "Your wish list has been submitted";
}
//inside the processitems() function of the main if statement, after the nested if statement, add a statement to increment the value of i by 1.
i += 1;
}
}
var btn = document.getElementById("button");
if (btn.addEventListener) {
btn.addEventListener("click", processitems, false);
} else if (btn.attachEvent) {
btn.attachEvent("onclick", processitems);
}
</script>
Related
I'm new to creating webpage. I was stuck in this part, where there are three link (should be visible) and three textbox(should be invisible) as default .
When I click one link only that respective text field should visible. if I click another link previous field should hide and it's respective text field should be visible.
Example
If click student link the respective student div should visible then if I click parent then previously student div should hide and parent div must visible.
This is my sample code.
<div>
<ul class="role" id="role">
<li class="selected">
student
</li>
< li>|</li>
<li class="">
teacher
</li>
<li>|</li>
<li class="">
parent
</li>
</ul>
</div>
<div class="block" id="student">
<input type="text" name="stud" id="Stud">
</div>
<div class="block" id="teacher">
<input type="text" name="teach" id="Teach">
</div>
<div class="block" id="parent">
<input type="text" name="par" id="par">
</div>
I think this is what you want.
var student = document.getElementById("student_tab");
var teacher = document.getElementById("teacher_tab");
var parent = document.getElementById("parent_tab");
var b_Stud = document.getElementById("Stud");
var b_Teach = document.getElementById("Teach");
var b_par = document.getElementById("par");
function clear() {
b_Stud.style.display = "none";
b_Teach.style.display = "none";
b_par.style.display = "none";
}
function show(type) {
switch (type) {
case "student_tab":
b_Stud.style.display = "block";
break;
case "teacher_tab":
b_Teach.style.display = "block";
break;
case "parent_tab":
b_par.style.display = "block";
break;
default:
break;
}
}
student.addEventListener("click", function(e) {
clear();
show(e.target.id);
});
teacher.addEventListener("click", function(e) {
clear();
show(e.target.id);
});
parent.addEventListener("click", function(e) {
clear();
show(e.target.id);
});
<div>
<ul class="role" id="role">
<li class="selected">
student
</li>
<li class="">
teacher
</li>
<li class="">
parent
</li>
</ul>
</div>
<div class="block" id="student">
<input type="text" name="stud" id="Stud" placeholder="Stud" />
</div>
<div class="block" id="teacher">
<input type="text" name="teach" id="Teach" placeholder="Teach" />
</div>
<div class="block" id="parent">
<input type="text" name="par" id="par" placeholder="par" />
</div>
Check this out.
const studentInput = document.getElementById("Stud");
const teacherInput = document.getElementById("Teach");
const parentInput = document.getElementById("par");
const links = document.querySelectorAll('a');
const hideInputs = () => {
const inputs = document.querySelectorAll('input');
inputs.forEach(input => input.classList.remove("active"));
}
const showElement = (e) => {
if(e.target.textContent === "parent") {
hideInputs();
parentInput.classList.add("active");
} else if(e.target.textContent === "student") {
hideInputs();
studentInput.classList.add("active");
} else if(e.target.textContent === "teacher") {
hideInputs();
teacherInput.classList.add("active");
}
}
links.forEach(link => link.addEventListener('click', (e) => showElement(e)))
input {
display: none;
}
input.active {
display: block;
}
<div>
<ul class="role" id="role">
<li class="selected">
student
</li>
<li class="">
teacher
</li>
<li class="">
parent
</li>
</ul>
</div>
<div class="block" id="student">
<input type="text" name="stud" id="Stud" placeholder="student" class="active">
</div>
<div class="block" id="teacher">
<input type="text" name="teach" id="Teach" placeholder="teacher">
</div>
<div class="block" id="parent">
<input type="text" name="par" id="par" placeholder="parent">
</div>
<div>
<div class=category> Birthdays </div>
<div class=category> Anniversaries </div>
<div class=category> Newborns </div>
<div class=category> Weddings </div>
</div>
<ul>
<li class="product-filter-items">Birthdays</li>
<li class="product-filter-items">Weddings</li>
<li class="product-filter-items">Newborns</li>
<li class="product-filter-items">Anniversaries</li>
</ul>
<script>
let proCatList = document.querySelectorAll(".category")
let proFilterItems = document.querySelectorAll(".product-filter-items")
for(let i = 0; i < proFilterItems.length; i++){
proFilterItems[i].addEventListener("click" , function(){
if (proCatList[i].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim() == proFilterItems[i].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim() ){
proFilterItems[i].classList.add("active-filter")
console.log("Class Added")
}
})
}
</script>
I am trying to add a class based on a click event. What I am trying to do is if classname, category and product-filter-items are equal then it should add a classname called active-filter on click. Can anyone point out why this statement does not recognise the textContent of proCatList?
The iteration param i can't be used in the event handler. Therefor you could use the index of the clicked element, which you can call with this.
For getting the index, you can use the following small function:
const getIndex = elem => [...elem.parentNode.children].indexOf(elem);
Working example:
let proCatList = document.querySelectorAll(".category");
let proFilterItems = document.querySelectorAll(".product-filter-items");
/* small function for getting the index */
const getIndex = elem => [...elem.parentNode.children].indexOf(elem);
for (let i = 0; i < proFilterItems.length; i++) {
proFilterItems[i].addEventListener("click", function() {
const elem_index = getIndex(this);
if (proCatList[elem_index].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim() == this.textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim()) {
this.classList.add("active-filter");
console.log("Class Added");
}
})
}
<div>
<div class=category> Birthdays </div>
<div class=category> Anniversaries </div>
<div class=category> Newborns </div>
<div class=category> Weddings </div>
</div>
<ul>
<li class="product-filter-items">Birthdays</li>
<li class="product-filter-items">Weddings</li>
<li class="product-filter-items">Newborns</li>
<li class="product-filter-items">Anniversaries</li>
</ul>
I've seen this question asked quite a bit, and I've followed all the recommendations but I can't seem to get it to work. My code is pretty simple at the moment, all it's doing is getting an input value from the input field, and updating the global variable. Any help would be great!
const createButton = document.getElementById('create-todo');
const errorOutput = document.getElementById('error-messages');
let taskValue = '';
const getInputValue = () => {
const inputValue = document.getElementById('task-input').value;
if(inputValue === ''){
errorOutput.innerHTML += `<p>Please Enter A Task</p>`;
}else{
taskValue = inputValue;
};
};
createButton.addEventListener('click', getInputValue);
console.log(taskValue);
<div id="root">
<header class="header">
<h1>To Do List</h1>
<input type="checkbox" class="toggle">
</header>
<main class="main">
<section class="todo-form">
<input type="text"
placeholder="Type your task..."
value = ""
id="task-input">
<button id="create-todo">Add To List</button>
</section>
<section id="error-messages"></section>
<section class="todo-list">
<ul>
<li id="todo-list-item">test item</li>
</ul>
<div class="list-buttons">
<button id="mark-completed">Mark As Completed</button>
<button id="remove-item">Remove Item</button>
</div>
</section>
<section class="completed-list">
<h2>Completed Tasks</h2>
</section>
</main>
<footer class="footer">
<button class="reset-button" id="reset">Clear List</button>
</footer>
</div>
That's because that line is executing immediately (before the click event has taken place). Move it into the getInputValue function so it runs at the right time.
Code in JavaScript does not necessarily execute linearly. Functions that are registered as event handlers (callbacks) only run when and if that event occurs, so that code is skipped over until needed. Your console.log() exists outside of that, so it is executed right away.
Yeah I tried that, and it doesn't update the variable after clicking
the button
Then you have another problem because as you can see below, it works as I describe if you simply move the code you want to run after the button is clicked into the button click handler.
document.getElementById('create-todo').addEventListener('click', () => {
if(task.value === ''){
errorOutput.innerHTML += `<p>Please Enter A Task</p>`;
}else{
taskValue = task.value;
}
console.log(taskValue); // <-- Works now!
}
);
const errorOutput = document.getElementById('error-messages');
const task = document.getElementById('task-input');
let taskValue = '';
<div id="root">
<header class="header">
<h1>To Do List</h1>
<input type="checkbox" class="toggle">
</header>
<main class="main">
<section class="todo-form">
<input type="text"
placeholder="Type your task..."
value = ""
id="task-input">
<button id="create-todo">Add To List</button>
</section>
<section id="error-messages"></section>
<section class="todo-list">
<ul>
<li id="todo-list-item">test item</li>
</ul>
<div class="list-buttons">
<button id="mark-completed">Mark As Completed</button>
<button id="remove-item">Remove Item</button>
</div>
</section>
<section class="completed-list">
<h2>Completed Tasks</h2>
</section>
</main>
<footer class="footer">
<button class="reset-button" id="reset">Clear List</button>
</footer>
</div>
When I type something in the first box, and click Next, the word I typed is inserted on my page. However, if I click Back and then click Next again, it is printed a second time.
I want the keyword appended after I've clicked Next to be deleted if I click Back so that if I click Next again it is printed only once (and updated if I have made any edit).
document.addEventListener("DOMContentLoaded", function() {
var stepOne = document.getElementsByClassName("step-1");
var stepTwo = document.getElementsByClassName("step-2");
var nextButton = document.getElementsByClassName("next");
var backButton = document.getElementsByClassName("back");
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
newKeyword.innerText = inputKeyword;
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
backButton[0].onclick = function() {
stepOne[0].style.display = "block";
stepTwo[0].style.display = "none";
}
})
.step-1 {
display: block;
}
.step-2 {
display: none;
}
<!--STEP 1-->
<div class="main step-1">
<div class="tab" id="tab-1">
<div class="inputFields">
<p id="jobtitle" class="inputFieldName">Job title</p>
<input type="search" id="inputJobTitle" class="inputBar" />
<p class="and">AND</p>
</div>
<div class="button">
<button class="next">Next ></button>
</div>
</div>
</div>
<!--STEP 2-->
<div class="main step-2">
<div class="tab" id="tab-1">
<div class="inputFields">
<div id="retrievedFields"></div>
<input type="search" class="inputBarAlternative" />
<div class="add">
<button class="addButton">+ Add Keyword</button>
<p id="addKeyword">
Add a skill or keyword that must be in your search results
</p>
</div>
</div>
<div class="buttons">
<button class="back">Back</button>
<button class="next">Next</button>
</div>
</div>
</div>
</body>
Each new click on the next button will trigger an append. So you just have to do the opposite of an append on the click on back. Just add this line in your onclick:
document.getElementById("retrievedFields").removeChild(document.getElementById("retrievedFields").lastElementChild);
You could also check to see if the element exists before you create it..
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.getElementById("retrievedField-1")
if (!newKeyword) {
newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
newKeyword.innerText = inputKeyword;
}
I am trying to create a list of names. As of now, my code is able to add one name at a time. I want to identify if there is a comma (,) on my input, so I can add add that second or third name and create an individual <li>, how can I identify if an input has a specific character?
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init(){
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField(){
var item = document.getElementById("addItems").value;
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(item));
list.appendChild(newField);
}
function extraInput(){
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1){
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
You can use string.split function. Working code below.
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init() {
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField() {
var item = document.getElementById("addItems").value;
if (item == "") {
alert("enter something");
return false;
}
var items = item.split(',');
for (i = 0; i < items.length; i++) {
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(items[i]));
list.appendChild(newField);
}
}
function extraInput() {
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1) {
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
Update: I didnt f5 to know it already answered. just ignore it.
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init(){
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField(){
var item = document.getElementById("addItems").value;
if(isValid(item )){
var itemArr = item.split(",");
for (var i = 0; i < itemArr.length; i++) {
element = itemArr[i];
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(element ));
list.appendChild(newField);
}
}
else{alert('invalid text!');}
}
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';/{}|\\":<>\?]/g.test(str);
}
function extraInput(){
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1){
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
try improve your function addField
function addField(){
var item = document.getElementById("addItems").value; //Get the string
var res = item.split(","); //split the string and create an array
res.forEach(function (value) { createField(value); }); //for each element in the array call to createField
}
function createField(text){
var list = document.getElementById("greatList"); // use local variable, not global
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(text));
list.appendChild(newField);
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>