Can anyone tell me what is wrong with my code? This works for all the other elements on the page but not this one, which is the parent to all of them.
let addButton = document.querySelector('.add-note');
addButton.addEventListener('click', (event) => {
//prevent refresh
event.preventDefault();
//note input value
let noteInput = document.querySelector(".note-input");
//create note container
let noteList = document.querySelector(".notes");
//create note
let note = document.createElement("li");
note.classList.add("note");
noteList.appendChild(note);
});
<div class="title">
<h1>To Do List</h1>
</div>
<br>
<form>
<div class="add-note">
<input class="note-input" type="text" placeholder="Enter to-do item here"></input>
<button class="add" type="submit">+</button>
</div>
</form>
<br>
<ul className="notes" id="notes"></ul>
Is this a React project? className is only available when using React.
<ul className="notes" id="notes"></ul>
change to
<ul class="notes" id="notes"></ul>
Your question i a tad unclear, but i think part of it is that you added the event listener to the div instead of the submit button. Change the class in your query selector to ".add" instead of ".add-note".
Related
I am making a TODO list. I have difficulties with setting the input text on my card. Everything I write in the input, I want to select and to put on the card.
I tried to select the innerHTML of an input when I type something in. I don't know how to select the typed input text. I would then create a new element with the text inside, and would append it to the card.
let btn = document.querySelector('.add');
let textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
// eventlistner by button clicked
btn.addEventListener('click', function() {
var txt = document.getElementsByClassName('input').innerHTML;
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<buton class="add" type="button"> + </buton>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
To get the value of the input use the value property, not innerHTML. Also note that you already have a reference to the input Element in the input variable, so you don't need to use getElementsByClassName() to retrieve it - not least of all because the syntax there is flawed.
Once you have the text you can use createElement() to add a new p element to the .todotext container:
const btn = document.querySelector('.add');
const textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
btn.addEventListener('click', function() {
const txt = input.value;
if (!txt)
return;
const p = document.createElement('p');
p.textContent = txt;
textspace.appendChild(p);
input.value = '';
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<button class="add" type="button"> + </button>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
As others already answered your question. I just wanted to point out that there is a misspelling in your code (buton instead of button). Fix that and the button element would be rendered correctly.
First, getElementsByClassName will return HTMLCollection which is array-like, you need to use querySelector instead, also the innerHTML, textContent, innerText properties all are empty string for the input because the input is a self-closing tag without content inside, you need to use value property.
let btn = document.querySelector('.add');
let textspace = document.querySelector('.todotext');
const input = document.querySelector('input');
// eventlistner by button clicked
btn.addEventListener('click', function() {
var txt = input.value;
console.log(txt)
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list"></ul>
<div class="addtodo">
<buton class="add" type="button"> + </buton>
<input type="text" class="input" placeholder="add todo" />
</div>
</div>
btn.addEventListener('click', function() {
var txt = document.getElementByClassName('input').value;
});
You were using getElementByClassName which will be HTMLCollection.To loop over each element you need to convert it into an array loop over them.
var txt = document.getElementsByClassName('input').value;
You should get the value of an input , not the innerHTML
Also assign a unique id to you input fields and select them with it, it's much better :)
I checked all the code and there is nothing wrong with it. When I check the "vegetables" radio button, write something in the text field and hit add, it doesn't add the element.
function add() {
var item;
item = document.getElementById("item").value;
if (document.getElementById("1").checked) {
var li = document.createElement(li);
text = document.createTextNode(item);
li.appendChild(text);
document.getElementById("1v").appendChild(li);
}
}
<section>
<h1>Welcome to your shopping List!</h1>
<h2>Type in the item, choose its type, and hit add !!</h2>
<div id="blue">
<form action="">
<label for="task">I need :</label><br>
<input type="text" placeholder="Example : Apples" id="item" name="item"><br>
<br>
<label for="type">which is :</label><br>
<div class="">
<input type="radio" id="1" name="type" value="Vegetables">
<label for="">Vegetables</label><br>
</div>
<br>
<button id="add" onclick="add()">Add !</button>
</section>
</form>
</div>
<br>
<footer id="white">
<div>
<table border="bold">
<th>Vegetables</th>
<tbody>
<tr>
<td>
<ol id="1v"></ol>
</td>
</tr>
</tbody>
</table>
</div>
</footer>
You have several problems:
You are using a form, so when you click the button, the form
submits and you leave the page. In your case, you aren't really going to submit data anywhere, so you really don't even need the form element or to specify name attributes for your fields.
You don't have li in quotes, so you aren't actually creating an
<li> element. Without quotes, the system thinks li is a variable, but since you don't have a variable called that, a new Global variable is created with a value of undefined, so your code executes as: document.createElement("undefined"), which does actually create: <undefined></undefined>, but since that isn't an actual HTML element, nothing is rendered for it, except the text you placed inside it (but no numbering):
var li;
let el = document.createElement(li);
console.log(el);
You are using label incorrectly. A <label> element correlates to a form-field element (i.e. input, select, textarea) as a way to have a "caption" for that element. To use it, you should set its for attribute to the id of the form-field its associated with or you can not use for and just nest the form-field its associated with inside of the label. label is not just for text you want to display.
Your HTML is not nested properly and you are missing elements.
Tables should really not be used for anything but displaying tabular
data. They should not be used for layout. Since you are creating new
ordered list items for each item added, you should not use a table.
But, even when you do, you can't just have th. th must be inside
of tr, which would then be inside of thead.
A footer element is meant to provide "the fine print" content at the end of a section. Producing your list isn't that kind of content and shouldn't be in a footer.
Here's all of that put toghether:
// Get your DOM references just once
const item = document.getElementById("item");
const list = document.getElementById("1v");
const veg = document.getElementById("type");
// Don't use inline HTML event attributes to set up events.
// Do your event binding in JavaScript, not HTML.
document.getElementById("add").addEventListener("click", add);
function add() {
if (veg.checked) {
var li = document.createElement("li"); // <-- Need quotes around the element name
li.textContent = item.value;
list.appendChild(li);
}
}
table,th,td { border:1px solid black; }
<section>
<h1>Welcome to your shopping List!</h1>
<h2>Type in the item, choose its type, and hit add !!</h2>
<div id="blue">
I need : <input type="text" placeholder="Example : Apples" id="item"><br>
<br>
which is : <input type="checkbox" id="type" value="Vegetables"> Vegetables
<div><button id="add">Add !</button></div>
</div>
</section>
<br>
<footer id="white">
<div>
Vegetables
<ol id="1v"></ol>
</div>
</footer>
2 quick fixes to your code (personally, I would rewrite the whole thing):
add type="button" to the button. It will prevent the button from defaulting to a submit.
Syntax error in var li = document.createElement(li);. the li should be in quotes:
var li = document.createElement('li');
I am working on a personal blog website project, and I wanted to implement a simple message board on my index page. Due to the projected site traffic (relatively low) I decided on only using a front-end implementation without linking to a database with the following js and html code:
<section class="message-board">
<div class="title">
<h2>
Leave a message
</h2>
</div>
<textarea class="message" type="text"></textarea><br/>
<input value="submit" type="button" class="submit-btn">
<div class="display-area">
Existing comment:
</div>
</section>
and then the js,
<script>
window.onload=function() {
var displayArea = document.getElementsByClassName("display-area");
var btn = document.getElementsByClassName("submit-btn");
btn.onclick = function() {
var comment = document.getElementsByClassName("message").value;
displayArea.appendChild(comment);
};
}
</script>
My intention was to make my display-area contain whatever was put in textarea via .appendChild when submit is clicked. Sadly, it isn't working as intended-nothing actually happens. I am thinking about potential errors in my js code, but just couldn't figure out anything that would resolve the problem.
Any assistance will be greatly appreciated!!!
getElementsByClassName() returns a collection of elements (note the s in Elements). If you have only one element that matches the class name, you have this element in the first index of the array-like collection.
var displayArea = document.getElementsByClassName("display-area")[0];
var btn = document.getElementsByClassName("submit-btn")[0];
You can also use querySelector(), that uses CSS selectors (like jQuery) and returns a single element:
var displayArea = document.querySelector(".display-area");
In order to append a text node (your variable comment stores a string), use append() instead of appendChild():
displayArea.append(comment);
Two ways this can be done are by calling the JavaScript function on click, or by calling it on form submission.
1) call function onclick:
Wrap your form within a form tag, and call your JavaScript function based on the element Ids.
Note the showInput function is being called onclick when the button is clicked.
function showInput() {
console.log('showInput called...')
var userInput = document.getElementById("userInput").value;
var display = document.getElementById("display");
display.innerHTML = userInput;
}
<section class="message-board">
<div class="title">
<h2>
Leave a message
</h2>
</div>
<form>
<textarea class="message" type="text" id="userInput"></textarea><br/>
</form>
<input type="submit" onclick="showInput();">
<div class="display-area">
Existing comment:
</div>
<p><span id="display"></span></p>
</section>
Here's a jsfiddle, with the same code as above: http://jsfiddle.net/ethanryan/94kvj0sc/
Note the JavaScript in the jsfiddle is being called at the bottom of the Head section of the HTML.
2) call function on form submit:
You can also do this by calling the JavaScript function on the submission of the form, instead of on the click of the button. However, since this form uses a textarea, hitting return will add a line break to the text, and not submit the form, so the button still needs to be clicked for the function to be called.
function showInput() {
console.log('showInput called...')
event.preventDefault()
var userInput = document.getElementById("userInput").value;
var display = document.getElementById("display");
display.innerHTML = userInput;
}
<section class="message-board">
<div class="title">
<h2>
Leave a message
</h2>
</div>
<form onsubmit="showInput()">
<textarea class="message" type="text" id="userInput"></textarea><br/>
<input type="submit" value="Submit">
</form>
<div class="display-area">
Existing comment:
</div>
<p><span id="display"></span></p>
</section>
Note the event.preventDefault() in the form, since the default behavior of forms is to submit data to a backend database.
jsfiddle: http://jsfiddle.net/ethanryan/qpufd469/
3. appending instead of replacing text
Finally, my examples above used innerHTML to replace the userInput text. If you want to append instead of replace the text, you can use insertAdjacentHTML to add the text to the end, and then append a linebreak to it. Finally, you can reset the form.
function showInput() {
console.log('showInput called...')
event.preventDefault()
var userInput = document.getElementById("userInput").value;
var display = document.getElementById("display");
var theForm = document.getElementById("theForm");
var linebreak = document.createElement("br");
display.insertAdjacentHTML('beforeend', userInput);
display.appendChild(linebreak);
theForm.reset();
}
<section class="message-board">
<div class="title">
<h2>
Leave a message
</h2>
</div>
<form onsubmit="showInput()" id="theForm">
<textarea class="message" type="text" id="userInput"></textarea><br/>
<input type="submit" value="Submit">
</form>
<div class="display-area">
Existing comment:
</div>
<p><span id="display"></span></p>
</section>
jsfiddle: http://jsfiddle.net/ethanryan/x4hq0Lzp/
right now I am a beginner in Javascript/Jquery.
I want to create a dynamic code, so that it will work when there comes some new features to the website without need to edit code.
Now i just read in some posts how to use a variable as identifier for id, but it is not working for me. So below is an example:
var category;
$('#mainCategory').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
...some code...
});
$("#"+category).change(function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
So the function mainCategory always runs before the other one and category got written correct in the 2nd function, when i am using the whole expression instead of using a variable.
I hope you can help me.
the part of html code:
<form method="post" action="../php/saveTraining.php">
<section id="mainCategory" class="hidden">
<label><input type="checkbox" id="Krafttraining">Krafttraining</label>
<label><input type="checkbox" id="Joggen">Joggen</label>
</section>
<section id="categoryKrafttraining" class="hidden">
<label><input type="checkbox">Kurzhantel</label>
<label><input type="checkbox">Bankdrücken</label>
<label class="hidden"><input type="number" id="saetze">Sätze</label>
<label class="hidden"><input type="number" id="wiederholungen">Wiederholungen</label>
</section>
<input type="hidden" id="saveTraining" name="sent" value="save" class="hidden"/>
</form>
So what actually happens is that when checking a checkbox of mainCategory the checkboxes of the second section appearing.
But when I check a checkbox of the second section nothing happens.
I thought I had the solution before but I see I was wrong. I believe this should work, where you re-add the listener as the value for the var category change:
var category;
$('#mainCategory input[type="checkbox"]').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
$('#' + category).find('input[type="checkbox"]').off("change").on("change", function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
});
You need to re-add the listener because new elements will be targeted as var category changes.
I have a html fragment similar to this
<div class="form-row">
<input type="text" id="foo1">
</div>
<div class="form-row">
<input type="text" id="foo2">
</div>
<div class="form-row">
<input type="text" id="foo3">
</div>
and I wanted to use cheerio to change the id tag to foobar[1,2,3]
my code is
var cheerio = require("cheerio");
var $ = cheerio.load("html as above");
var inputs = $('input[id]');
Object.keys(inputs).forEach(function(key,index) {
if (key == index) {
console.log(key,inputs[key])
//#1
});
at this point (//#1), I wanted to get the value of the id attribute, and according to the docs at https://github.com/cheeriojs/cheerio I can use the .data method to get and change the attribute in the element, but
inputs[key].data("id")
gives me a "TypeError: undefined is not a function" error
I know that I'm missing something simple, but can't see the wood for the trees and would appreciate some pointers.
thanks
update #1
just when I think I've got a grip on this, it slips from my fingers ..
now, I want to move an element :
I have
<label>xyz<i class="fa fa-list"></i></label>
and I want
<label>xyz</label><i class="fa fa-list"></i>
the code - that doesn't work ;) - is this
var icons = $('label i');
icons.each(function(index,icon) {
// #2 now that I've got an element what now ?
}
I know that icons.remove() will delete the element(s) but struggling to get them added to the right place.
The problem is inputs[key]) will be a dom element reference, which will not have methods like data()
Try to set the attribute value like
var cheerio = require("cheerio");
var $ = cheerio.load('<div class="form-row">\
<input type="text" id="foo1">\
</div>\
<div class="form-row">\
<input type="text" id="foo2">\
</div>\
<div class="form-row">\
<input type="text" id="foo3">\
</div>');
var inputs = $('input[id]');
inputs.attr('id', function(i, id){
return id.replace('foo', 'foobar')
});
console.log($.html())