I am currently using an add button to add input from a text box into a list. I am also binding a button to each of these list elements and then appending them to the unordered list. How do I remove the element onclick of the corresponding remove button? Pure JavaScript only.
window.onload = function() {
var elements = [];
var textInput;
document.getElementById("addButton").onclick = function() {
textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
}
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<!DOCTYPE html>
<html>
<body>
<head>
<script src="func.js"></script>
</head>
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>
</body>
</html>
Use addEventListener to register click event over created button.
Use .remove(), removes the object from the tree it belongs to.
Try this:
window.onload = function() {
var elements = [];
document.getElementById("addButton").onclick = function() {
var textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
btnNode.addEventListener('click', removeHandler);
}
}
function removeHandler() {
this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>
Related
So i have following objectives from the checkbox click event
1] Create A Button having id = 'id-of-checkbox'+'some-character-here' in specified div
2] Clicking On That Particular Button Will Remove The Button As Well As Checkbox tick related to it
3] If User wants to remove button in specified div through unchecking the checkbox it should be done
4] And If User again checks the checkbox button should be created in specified div
Now i have achieved first 3 objectives and im having issue with 4th one , i.e
if i click on checkbox again after unticking it button is not getting created and console doesnt return any error associated with it.. please help
Here Is My HTML Code
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)">
Price Filter
</div>
<div id="DropArea">
</div>
Here is My Javascript Code
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id,name)
{
if(document.getElementById(id).checked)
{
checked='yes'
}
else if(!document.getElementById(id).checked)
{
checked='no'
}
if(checked=='yes')
{
addButton(id,name);
}
else if(checked=='no')
{
removeButton(id,name);
}
}
function addButton(id,name)
{
var nameOfButton = name+'X';
var idofButton = id+'11';
var btn = document.createElement("BUTTON");
btn.innerHTML=nameOfButton;
btn.setAttribute("class","btnCancel");
btn.setAttribute("id",idofButton);
btn.setAttribute("onclick","someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id,name)
{
var idofButton = id+'11'
if(document.getElementById('DropArea').contains(document.getElementById(idofButton)))
{
document.getElementById('DropArea').remove(document.getElementById(idofButton));
console.log('Button Removed');
}
}
function someMsg(id)
{
var name = id.substring(0,id.length-2);
document.getElementById(id).remove();
document.getElementById(name).checked=false;
console.log('Deleted');
}
Another approach to achieving the same result:
const dropArea = document.querySelector("#dropArea");
const checkbox = document.querySelector("#priceFilter");
checkbox.addEventListener("change", function(e) {
if (this.checked) {
const btn = createSpecificButton();
dropArea.appendChild(btn);
} else {
const btn = dropArea.querySelector("button");
dropArea.removeChild(btn);
}
});
const createSpecificButton = () => {
const btn = document.createElement("button");
btn.innerText = "Click Here";
btn.addEventListener("click", function(e) {
checkbox.checked = false;
this.remove();
});
return btn;
};
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" /> Price Filter
</div>
<div id="dropArea"></div>
Element.remove() don't have any parameters, so when you call by your way, it will remove DropArea element (includes children, like idofButton).
Solution: Change the below line
document.getElementById('DropArea').remove(document.getElementById(idofButton));
To
document.getElementById(idofButton).remove();
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id, name) {
if (document.getElementById(id).checked) {
checked = 'yes'
} else if (!document.getElementById(id).checked) {
checked = 'no'
}
if (checked == 'yes') {
addButton(id, name);
} else if (checked == 'no') {
removeButton(id, name);
}
}
function addButton(id, name) {
var nameOfButton = name + 'X';
var idofButton = id + '11';
var btn = document.createElement("BUTTON");
btn.innerHTML = nameOfButton;
btn.setAttribute("class", "btnCancel");
btn.setAttribute("id", idofButton);
btn.setAttribute("onclick", "someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id, name) {
var idofButton = id + '11'
if (document.getElementById('DropArea').contains(document.getElementById(idofButton))) {
document.getElementById(idofButton).remove();
console.log('Button Removed');
}
}
function someMsg(id) {
var name = id.substring(0, id.length - 2);
document.getElementById(id).remove();
document.getElementById(name).checked = false;
console.log('Deleted');
}
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)"> Price Filter
</div>
<div id="DropArea">
</div>
So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";
i have been trying to clear the text box after pressing the enter key, but i couldn't find any solution for this, been searching for over 2 hours.. this is the code:
html:
<!DOCTYPE html>
<html>
<body>
<style>
input{
margin-top:300px;
margin-left:580px;
}
ul{
margin-left:580px;
}
</style>
<input type="text" id="textBox" value = "" />
<ul id="dynamic-list"></ul>
<script src="script.js"></script>
</body>
</html>
javascript:
function addItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("textBox");
var li = document.createElement("li");
li.setAttribute('id',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
document.getElementById('candidate').value = "";
document.getElementById('textBox').value = "";
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
addItem();
}
});
There is no element whose ID is candidate in your HTML code. So JavaScript throws and error and stops executing the next statement. That's why the textbox doesn't clean up.
Remove the buggy statement, and your code works just fine:
function addItem() {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("textBox");
var li = document.createElement("li");
li.setAttribute('id', candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
document.getElementById('textBox').value = "";
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
addItem();
}
});
<input type="text" id="textBox" value="" />
<ul id="dynamic-list"></ul>
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.
var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');
function store(ele) {
if (event.keyCode == 13) {
changeText();
}
}
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate();
}
}
function changeDate() {
var d = new Date();
var dates = document.createElement("div");
dates.className = "myClass";
dates.innerHTML = document.createTextNode(d.toDateString());
list2.innerHTML = dates;
}
<div class="container">
<h1>
Your todos
</h1>
<input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
<div class="todos">
<ul id="demo"></ul>
</div>
</div>
First of all your JS has an issue. The list2 is a HTMLCollection and there's no .innerHTML for that. You need to use:
list2[0].innerHTML
You don't even need that. The date issue is because of the Date Object incorrectly being set / inserted.
var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');
function store(ele) {
if (event.keyCode == 13) {
changeText();
}
}
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate(list);
}
}
function changeDate(which) {
var d = new Date();
which.innerHTML += d.toDateString();
}
<div class="container">
<h1>
Your todos
</h1>
<input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
<div class="todos">
<ul id="demo"></ul>
</div>
</div>
Preview
instead of this:
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
changeDate(list);
}
}
try this:
function changeText() {
var data = document.getElementById('todo').value;
if (data != '') {
var entry = document.createElement('li');
changeDate(list); //call this before appending data
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
}
}
and CSS:
li{
display: inline-block;
}
I am having a tough time with this javascript code to change the background color of a text input if the input is empty.
Here is the code:
function checkFilled() {
var inputVal = document.getElementById("subEmail").value;
if (inputVal == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Example: http://jsfiddle.net/2Xgfr/
I would expect the textbox to come out yellow at the beginning.
DEMO --> http://jsfiddle.net/2Xgfr/829/
HTML
<input type="text" id="subEmail" onchange="checkFilled();">
JavaScript
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
else{
inputVal.style.backgroundColor = "";
}
}
checkFilled();
Note: You were checking value and setting color to value which is not allowed, that's why it was giving you errors. try like the above.
You didn't call the function and you have other errors, should be:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
Fiddle
You were setting inputVal to the string value of the input, but then you tried to set style.backgroundColor on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.
on body tag's onLoad try setting it like
document.getElementById("subEmail").style.backgroundColor = "yellow";
and after that on change of that input field check if some value is there, or paint it yellow like
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Try this:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Don't add styles to value of input so use like
function checkFilled() {
var inputElem = document.getElementById("subEmail");
if (inputElem.value == "") {
inputElem.style.backgroundColor = "yellow";
}
}
<! DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="subEmail">
<script type="text/javascript">
window.onload = function(){
var subEmail = document.getElementById("subEmail");
subEmail.onchange = function(){
if(subEmail.value == "")
{
subEmail.style.backgroundColor = "red";
}
else
{
subEmail.style.backgroundColor = "yellow";
}
};
};
</script>
</body>
You could have the CSS first style the textbox, then have js change it:
<input type="text" style="background-color: yellow;" id="subEmail" />
js:
function changeColor() {
document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}
// program to change color of txtbox if empty string submitted
function chgColor() {
let x = document.getElementById("txt").value;
if (x == "") {
document.getElementById("txt").style.backgroundColor = "yellow";
}
}
<input type="email" name="hi" value="hi" id="txt">
<button type="button" onclick="chgColor();">ok</button>
You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property.
addRemoteImage = function(event) {
var textbox = document.querySelector("input[name='input-image']"),
imageUrl = textbox.value,
errorDiv = document.querySelector("div[name='input-image-error']");
if (imageUrl == "") {
errorDiv.style.display = "block";
textbox.classList.add('text-error');
setTimeout(function() {
errorDiv.style.removeProperty('display');
textbox.classList.remove('text-error');
}, 3000);
} else {
textbox.classList.remove('text-error');
}
}
.no-image-url-error {
color: red;
display: none;
}
.text-error {
border: 1px solid red !important;
}
<div class="div-image-background">
<div class="div-image-text">
<input class="input-image-url" type="text" placeholder="Add text" name="input-image">
<input type="button" onclick="addRemoteImage(event);" value="Submit">
</div>
<div class="no-image-url-error" name="input-image-error">Textbox empty</div>
</div>