This code creates a nested input within a list element but the placeholder doesn't display:
var li = document.createElement('li');
this._new_input_tag = document.createElement('input');
li.className = 'tagger-new';
li.placeholder = "Write here";
I tried
document.getElementById('tagger-new').placeholder = "Write here";
but that removed the input entirely.
Thanks for your help!
the reason why there is error in you code you put there something which is don't clear this key word while you were creating element
input = document.createElement('input');
input.setAttribute('placeholder', 'Write Here...');
document.body.appendChild(input)
you need to use append child run snippet below
function myFunction() {
var node = document.createElement("LI");
var inputnode = document.createElement("input");
inputnode.placeholder = "Write here"
node.appendChild(inputnode);
document.getElementById("myList").appendChild(node);
}
<ul id="myList">
</ul>
<p>Click the button to append an input to the end of the list.</p>
<button onclick="myFunction()">Try it</button>
Related
I'm trying to create a simple Javascript program that adds/removes items to an array, then displays the array by DOM manipulation.
I've created a reference called 'input', that is supposed to be the value of the HTML text input field. It's supposed to look like this:
let input = document.getElementById("text").value;
When I try to identify that variable in the console, it recognizes it as undefined. But, if I reference the variable like this:
let input = document.getElementById("text");
and call, input.value, it shows the appropriate value. For ex: "Lorem ipsum". What am I doing wrong?
I've provided a codepen link to see the output.
HTML
<div>
<form>
<input type ="text" id="text">
<button onClick="updateList(input.value)" type ="button">Add</button>
<button onClick = "reset()" type="button">Clear</button>
</form>
</div>
<div id='para'>
<!--list goes here-->
</div>
Javascript
//input.value will be used
let input = document.getElementById("text");
let groceryList = ["Grapes", "Juice", "Apples"];
//Div where output will be placed
let para = document.getElementById('para');
//Creation of ul
let unorderedList = document.createElement('ul');
para.appendChild(unorderedList);
//Creates list on DOM
const createList = groceryList.forEach((grocery) =>
{
//Creation of list item
let li = document.createElement('li');
li.innerText = grocery; // For instance, just to give us something to see
li.className = "grocery-item";
unorderedList.appendChild(li);
});
//Resets para
const reset = () => {
para.removeChild();
}
//Adds item
const updateList = (item) => {
reset();
groceryList.push(item);
return createList;
}
If you use let input = document.getElementById("text").value; you assign the initial value of your input field which is undefined at start to your variable.
This value will never change.
If you use let input = document.getElementById("text"); you set a reference to the input field to your variable and you can then retrieve the current value of this element by using input.value
I hope that my answer will be understandable because my English is really poor.
I intended to make a todo list but I'm getting a problem that i wanna make a button that come inline in list item like so <li>my task</li><button>Delete</button>
but my delete button isn't deleting items correctly it only deletes one items and then start giving error
this is my code, please look here and also tell me what kind of mistakes I'm doing I'm very beginner in web development
<!DOCTYPE html>
<html>
<body>
<input type="text" placeholder="Enter Task" onfocus="this.value=''" id="myTask">
<button onclick="myFunction()">Try it</button>
<button onclick="deleteTask()">del it</button>
<ol id="myList">
</ol>
<script>
function myFunction() {
var node = document.createElement("LI");
var myTask = document.getElementById("myTask").value;
var textnode = document.createTextNode(myTask);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
var btn = document.createElement("input");
var abcElements = document.querySelectorAll('LI');
for (var i = 0; i < abcElements.length; i++){
abcElements[i].id = 'abc-' + i;
}
// node.setAttribute("id", "li1");
btn.setAttribute("type", "submit");
btn.setAttribute("value", "delete");
btn.setAttribute("id", "delete");
node.appendChild(btn);
btn.addEventListener('click', ()=>{
// console.log("OK");
document.getElementById("abc-0").parentNode.removeChild(document.getElementById("abc-0"))
})
}
function deleteTask() {
var i = 0;
var item = document.getElementsByTagName("LI")[i];
i++;
item.parentNode.removeChild(item);
}
</script>
</body>
</html>
So I just want to make a delete button with every list item as I click on Try it button
Some points to address:
Don't call a function myFuntion. Give it a descriptive name, like addTask
Don't create id-attributes with sequential numbers. That is almost never needed.
The initial HTML should not have a delete button, since it should associate with a list item.
Don't make the type of the delete button "submit". That only makes sense when you have a form element, and need to submit the form.
Don't give the created button the same id over and over again: that is invalid in HTML. id-attributes should have unique values. But again, it is rarely needed to assign an id to dynamically generated elements.
In an event listener you can use the event object to get the element on which the event was fired. Or you can use the this object in a function. But you can also reference the node variable that exists in the so-called closure.
function addTask() {
var node = document.createElement("LI");
node.textContent = document.getElementById("myTask").value;
var btn = document.createElement("button");
btn.textContent = "delete";
btn.addEventListener('click', () => node.remove());
node.appendChild(btn);
document.getElementById("myList").appendChild(node);
}
li > button { margin-left: 5px }
<input type="text" placeholder="Enter Task" onfocus="this.value=''" id="myTask">
<button onclick="addTask()">Add task</button>
<ol id="myList"></ol>
try something like this:
function myFunction() {
const li = document.createElement("li");
li.innerHTML = document.getElementById("myTask").value;
const button = document.createElement("button");
button.innerHTML = "delete";
li.appendChild(button);
button.addEventListener("click", () => li.parentNode.removeChild(li));
document.getElementById("myList").appendChild(li);
}
The exercise says that my button (like a submit) must use the information set by user in input tag and create an li tag with the text as content. It was my first JavaScript class, so I'm still not familiarised with the syntax.
This is my actual code. I used a querySelector with the id of my existing ul tag, and addEventListener to create an event for the click action. I can't remember how to properly create the new li tag, and don't know how to use the content as info for it.
let myElement = document.querySelector('#add-book');
myElement.addEventListener("click", (e) => {
if (e.target.classList == 'button-add') {
let liElement = document.createElement('li');
let content = document.appendChild(liElement);
content.textContent();
}
});
I hope the button works properly, and show the element in the page by clicking the button (with the typed information).
Oversimplified, but hey, it works:
function AddLi(str)
{
var li = document.createElement('li');
li.appendChild(document.createTextNode(str))
li.innerHTML += ' <button onclick="this.parentNode.remove()">-</button>';
document.getElementById("out").appendChild(li);
}
<form>
<input type="text" name="userinput">
<input type="button" value="Add LI" onclick="AddLi(userinput.value)">
</form>
<span id="out"/>
I guess this is what you want:
(function () {
document.querySelector('#add').addEventListener('click', function () {
let input = document.querySelector('#text');
let list = document.querySelector('#list');
let item = document.createElement('li'); // create li node
let itemText = document.createTextNode(input.value); // create text node
item.appendChild(itemText); // append text node to li node
list.appendChild(item); // append li node to list
input.value = ""; // clear input
});
})();
<div>
<input id="text" type="text" />
<button id="add">Add</button>
</div>
<ul id="list">
<li>example item</li>
</ul>
But please, in the future, ask more specific questions. I don't even know what your problem is, because you don't provide all your code. Also the last sentence of your question is telling me nothing useful at all (.. "I hope the button works properly, and show the element in the page by clicking the button (with the typed information) " ..).
Try
function addBook(book) {
list.innerHTML +=
`<li>${esc(book.value)} <button onclick="del(this)">Del</button></li>`;
book.value = '';
}
function del(item) {
item.parentNode.remove();
}
function esc(s) {
return s.replace(/[&"<>]/g,c =>
({'&':"&",'"':""",'<': "<",'>':">"}[c]));
}
<ul id="list"></ul>
<input id="data" type="text" />
<button onclick="addBook(data)">Add</button>
Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}
I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>