This solution below works for adding and removing list items. I had to implement Math.random() in order to set a unique id for each element. I was thinking in the professional world this definitely wouldn't cut it considering the chance of a repeating ID.
Wanted to know what would be a more suitable implementation? Any feedback welcome!
Thanks!
HTML
<html>
<head>
<body>
<p id = 'listTitle'> Your List </p>
<form onsubmit = "return false">
<input id = 'inputBar' type = "text" placeholder = "Enter Item"></input>
<input type = "submit" onclick = "getName()"></input>
<input type = "button" value = "Remove" </input>
</form>
<ol id = 'demo'>
</ol>
</body>
</head>
</html>
JS
function getName() {
var input = document.getElementById('inputBar').value
var list = document.getElementById('demo')
var entry = document.createElement('li')
entry.setAttribute("id", Math.floor(Math.random()* (100 - 1) + 1 ))
console.log(entry.id)
entry.setAttribute("onclick", "removeName(this.id)")
entry.appendChild(document.createTextNode(input))
list.appendChild(entry)
}
function removeName(removeID) {
var listItem = document.getElementById(removeID)
listItem.remove()
}
There's no need for dynamic IDs. When appending the new element, just attach a listener that calls entry.remove() when clicked. You can also assign to the textContent instead of using the unnecessarily verbose createTextNode / appendChild.
function getName() {
const inputValue = document.getElementById('inputBar').value;
const li = document.getElementById('demo').appendChild(document.createElement('li'));
li.onclick = () => li.remove();
li.textContent = inputValue;
}
<p id='listTitle'> Your List </p>
<form onsubmit="return false">
<input id='inputBar' type="text" placeholder="Enter Item"></input>
<input type="submit" onclick="getName()"></input>
<input type="button" value="Remove" </input>
</form>
<ol id='demo'>
</ol>
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'm writing cart-box that will change the quantity of products in cart. It works only if I have one box (one product) in cart, but when I have more products in cart it changes the value of the first input only.
This is my html code (earlier in the code I've got loop for my products):
<div class="amount">
<a>
<button type="button" class="minus">-</button>
</a>
<input class="amount-input" th:type="text" th:value="1" th:min="1"/>
<a>
<button type="button" class="plus">+</button>
</a>
</div>
And this is JS code:
$('.minus').click(function () {
var parent = $(this).parent().parent();
var input = parseInt(parent.find(".amount-input").val());
var count = input - 1;
//input['value'] = count;
//parent.closest("input").value = count;
document.querySelector("input").value = count;
});
$('.plus').click(function () {
var parent = $(this).parent().parent();
var input = parseInt(parent.find(".amount-input").val());
var count = input + 1;
//input['value'] = count;
//parent.closest("input").value = count;
document.querySelector("input").value = count;
});
I know that document.querySelector("input").value = count changes the first input only, because it's first on the list, but input['value'] = count doesn't change anything, parent.closest("input").value = count either.
Make sure you use valid HTML, otherwise results are not guaranteed.
Next let's remove duplication and just use the one event listener for both buttons, changing the value added based on the presence of the plus class.
Finally, if you're using jQuery, stick to using jQuery methodology. Also, you are doing nothing here with jQuery that couldn't be done with simple, native, javascript.
//Use one event listener for both
$('.amount button').click(function () {
//Find the nearest ancestor with class amoun
var parent = $(this).closest(".amount");
//Note you need to still use $ with jQuery Objecyd
var input = $(parent).find(".amount-input");
//Set the count based on the class of the button click
var count = parseInt($(input).val()) + ($(this).hasClass("plus") ? 1 : -1 );
//Set the value
$(input).val(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="amount">
<button type="button" class="minus">-</button>
<input class="amount-input" type="text" value="1" min="1"/>
<button type="button" class="plus">+</button>
</div>
<div class="amount">
<button type="button" class="minus">-</button>
<input class="amount-input" type="text" value="1" min="1"/>
<button type="button" class="plus">+</button>
</div>
I created a page with a form, where you can enter a name.
When you submit the name, the name is stored under the name "bezeichnung".
Now i want to use the the input "bezeichnung" as a button label. And append it to the body of the page.
This is the form:
<head>
<link rel="stylesheet" href="\User\stl.css"/>
</head>
<body>
<h1> Neue Station hinzufügen</h1>
<form id="stationenformular" name="stationenformular" action="indexAktualisierung.html" method="get">
<div>
<label for="bezeichnung">Bezeichung der neuen Station:</label>
<input type="text" id="bezeichnung" name="bezeichung" />
</div>
<br><br>
<div>
<label for="ipadresse"> IP Adresse des Raspberry Pi:</label>
<input type="text" id="ipadresse" name="ipadresse"/text>
</div>
<div>
<br>
<input type="submit" value="Abschicken"/>
</div>
</form>
</body>
</head>
and this the function in another html script:
var x = document.getElementsByName("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
For first your name is bezeichung, not bezeichnung.
Also getElementsByName returns an array-like object. You need to get the first item from your elements;
var x = document.getElementsByName("bezeichnung")[0]; // Get the first
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x.value); // Create a text node with x's value
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
See example. I added text by default.
var x = document.getElementsByName("bezeichnung")[0];
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x.value); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
<body>
<h1> Neue Station hinzufügen</h1>
<form id="stationenformular" name="stationenformular" action="indexAktualisierung.html" method="get">
<div>
<label for="bezeichnung">Bezeichung der neuen Station:</label>
<input type="text" id="bezeichnung" name="bezeichnung" value="Test"/>
</div>
<br><br>
<div>
<label for="ipadresse"> IP Adresse des Raspberry Pi:</label>
<input type="text" id="ipadresse" name="ipadresse"/text>
</div>
<div>
<br>
<input type="submit" value="Abschicken"/>
</div>
</form>
</body>
To get a unique instance of the bezeichnung input field, you could use var x = document.getElementsByName("bezeichnung")[0]; or var x = document.getElementById("bezeichnung");
As Suren Srapyan said, getElementsByName returns an array of all elements with that name, so you need to specify which one you mean by putting the position in the array of the object you want.
However, as you presumably only want one instance of bezeichnung, it's easier to use getElementById.
var x = document.getElementsByName("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode(x); // Create a text node
btn.parentNode.insertBefore(t, btn); // Append the text to <button>
document.body.appendChild(btn);
Try to change getElementsByName with getElementById
var x = document.getElementById("bezeichnung");
var btn = document.createElement("BUTTON"); // Create a <button> element
btn.innerText = x.value; // Append the text to <button>
document.body.appendChild(btn);
Demo
I'm trying to create an HTML form which takes the text from multiple textboxes (in this case, 3) and adds the content of each to a list in a separate div, as well as create a new object "employee", all via the click of a button. My goal is to imitate adding employees to a database, using an employee id, first name, and last name as variables. I am looking to accomplish this using pure javascript.
What I have so far is:
<form>
ID Number:
<br>
<input type="text" id="idNumber">
<br>First name:
<br>
<input type="text" id="firstName">
<br>Last name:
<br>
<input type="text" id="lastName">
</form>
<br>
<button type="submit" onclick="myFunction(list)">Submit</button>
<div id="container">
<ul id="list"></ul>
</div>
In a separate JavaScript file:
function myFunction(list){
var text = document.getElementById("idNumber","fName","lName").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").replaceChild(li);
}
When I debug my code it seems to be setting the values fine, but I receive no actual output of my list.
None of the input elements you selected had a class name. You can also do this with document.getElementById. Just add ids to all your form elements.
Your code should look something like this.
function myFunction(list){
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
http://jsfiddle.net/nb5h4o7o/3/
Your list wasn't being appended to because you weren't actually creating the elements. replaceChild should have been appendChild and you should have created a list element with document.createElement.
Your code is full of problems, look at the document.getElementById and Node.replaceChild docs.
I've created a version for you that we get all the input elements of your form (using querySelectorAll), and then we use Array.prototype.map to turn them into "<li>[value]</li>", and then Array.prototype.join to turn that array into a single string.
Then, we get that string and set the #list.innerHTML property.
document.querySelector('button').addEventListener('click', function(e) {
var form = document.querySelector('form'),
list = document.getElementById('list');
list.innerHTML = [].map.call(form.querySelectorAll('input'), function(el) {
return '<li>' + el.value + '</li>';
}).join('');
});
<form>
ID Number:
<br>
<input type="text" id="idNumber">
<br>First name:
<br>
<input type="text" id="firstName">
<br>Last name:
<br>
<input type="text" id="lastName">
</form>
<br>
<button type="submit">Submit</button>
<div id="container">
<ul id="list"></ul>
</div>
I am new to Javascript. And I am trying to create a page which is used for writing reviews. I am stuck at a certain point.
There should be a button to add a section which copies the whole sections div to allow the user to write another section.
Attached below is my code. I am using CKeditor plugin to allow the end user to format their text as they wish.
The current code , while creating a new section, doesn't allow the user to write into the text area created. Please guide me as to where I was mistaken.
<?php
include 'settings.php';
if (!isset($dbc)){
$dbc = new mysqli(DB_HOST , DB_USER , DB_PASSWORD , DB_NAME);
}
if ($dbc -> connect_error){
die ("Cannot connect to the database");
}
?>
<html>
<head>
<title>Write a new Review.</title>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<form id = "new_review" action = "form.php" method = "post">
<div id = "header">
<h2> Header Section. </h2>
Author : <input type = "text" id = "author"> <br>
Title: <input type = "text" id = "title"> <br>
Tagline: <input type = "text" id = "tagline" > <br>
Score: <input type = "text" id = "score" > <br>
Pros: <textarea class = "ckeditor" id = "pros">
Please enter the pro's of the product here.
</textarea>
Cons: <textarea class = "ckeditor" id = "cons">
Please enter the cons of the product here.
</textarea>
Verdict:<textarea class = "ckeditor" id = "verdict">
Enter your vedict here.
</textarea>
</div>
<div id = "sections">
<h2> Sections. </h2>
<input type = "button" id="button" onclick="duplicate()">Add a section</button>
<div class = "section_base" id = "section">
Section Icon: <input type="file" id="icon" accept="image/*"> <br>
Section Title: <input type = "text" id = "section_title" > <br>
Section Text: <textarea class = "ckeditor" id = "section_text">
Enter you text here.
</textarea>
Section Score: <input type = "text" id = "section_score">
</div>
</div>
<div id = "conclusion">
<h2> Conclusion: </h2>
<textarea class = "ckeditor" id = "conclusions">
Enter your conclusion here.
</textarea>
</div>
<input type = "submit" value="submit">
</form>
<script type="text/javascript">
var i = 0;
var original = document.getElementById('section');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "section" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
</html>
Below are the links from where I had the information to do what I did.
http://ckeditor.com/ckeditor_4.3_beta/samples/replacebyclass.html
How can i duplicate a div onclick with javascript?
Try your javascript as this
<script type="text/javascript">
var i = 1;
function duplicate() {
var clone = '<div class = "section_base" id = "section">Section Icon: <input type="file" id="icon" accept="image/*"> <br> Section Title: <input type = "text" id = "section_title" > <br> Section Text: <textarea id = "section_text'+i+'"> Enter you text here. </textarea>Section Score: <input type = "text" id = "section_score"> </div>';
var div = document.getElementById('sections');
var newdiv = document.createElement('div');
newdiv.innerHTML = clone;
div.appendChild(newdiv);
CKEDITOR.replace('section_text'+i);
i++;
}
</script>
Seems like CKEditor got some issues with binding the controls for dynamically added elements. You can refer to this problem which contains discussion from people facing similar issues and their solutions.
CKEDITOR inline on dynamic created element ( droppable/sortable )
Also found this jsfiddle demo, which binds CKEditor inline
CKEDITOR.inline( el.get( 0 ) );
The guy has also written a nice tutorial on how to add inline ckeditor on dynamically created elements
See if it helps...