how to remove an object by button? - javascript

i built two buttons with this values("+" and "-")
when i click on "+" it creates a text and combo box,
i wanna know how to remove them with "-" button?(by only JavaScript)
here's the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>create and delete</title>
<script type="text/javascript">
/*this function creates text box and combo box*/
function cre()
{var t=document.createElement('select');
var form=document.getElementById('theForm');
var label = document.createElement('label');
var textbox = document.createElement('input');
form.appendChild(t);
form.appendChild(textbox);}
function del()
/*{delete t,form,label,textbox;}*/
</script>
</head>
<body>
<form id='theForm'>
<input type="button" value="+" onclick="cre()" />
<input type="button" value="-" onclick="del()" />
</form>
</body>
</html>

function del()
{
var form=document.getElementById('theForm');
var t = form.getElementsByTagName('select');
var textbox = form.getElementsByTagName('input');
if(t != 'undefined' && textbox != 'undefined')
{
form.removeChild(t[t.length-1]);
form.removeChild(textbox[textbox.length-1]);
}
}
Fiddle for your reference

My solution :
cre = function() {
var form = document.getElementById('theForm'),
div = document.createElement('div'),
t = document.createElement('select'),
label = document.createElement('label'),
textbox = document.createElement('input');
div.className = 'divContainer';
div.appendChild(t);
div.appendChild(label);
div.appendChild(textbox);
form.appendChild(div);
}
/*{delete t,form,label,textbox;}*/
delForm = function() {
var form = document.getElementById('theForm');
form.parentNode.removeChild(form);
}
del = function() {
var containers = document.getElementsByClassName('divContainer');
for(var i = 0; i < containers.length; i++) {
if(typeof(containers[i]) === 'object') {
containers[i].parentNode.removeChild(containers[i]);
}
}
}
JSFiddle : http://jsfiddle.net/j6Fxc/27/

Related

Alert message not being displayed by duplicate function when user enters duplicated values

I've been racking my brains trying to understand why my duplicate function isn't working. If everything worked as it should be the user should get an alert message each time s/he inputs a value twice. I tried to use the forEach method but the console kept throwing errors. So I'm now using good old for loop. No alert message being displayed either but at least the console isn't throwing any error, which I think is a step in the right direction.
var elUlList = document.getElementById("uList");
var btn = document.getElementById("btn");
const elInput = document.getElementById("input");
const footer = document.querySelector("footer");
const message = document.getElementById("message");
const elements = document.getElementsByTagName("li");
const elCounter = document.getElementById("counter");
function createListItems() {
var inputValue = elInput.value;
var newLi = document.createElement("li");
var newText = document.createTextNode(inputValue);
newLi.appendChild(newText);
elUlList.appendChild(newLi);
var array = Array.from(elements);
function findDuplicates() {
var compare = [];
for (var i = 0; i < array.length; i++) {
if(!compare.includes(array[i].textContent)){
compare.push(array[i].textContent)
} else {
alert("Value already entered")
}
}
}
if(inputValue === "") {
message.innerHTML = "field can't be left empty"
}
inputValue = ""
elCounter.innerHTML =+ elements.length;
}
btn.addEventListener("click", createListItems, false);
elInput.addEventListener("keyup", function(e) {
if(e.keyCode === 13) {
e.preventDefault();
btn.click()
}
})
elInput.addEventListener("mouseover", emptyField, false)
function emptyField() {
this.value = "";
}
elUlList.addEventListener("dblclick", function(e){
var target = e.target;
var parent = target.parentNode;
alert("are you sure you want to remove this item from the list")
parent.removeChild(target)
elCounter.innerHTML =+ elements.length;
});
elUlList.addEventListener("click", function(e){
var elements = document.getElementsByTagName("li");
var child = e.target;
if(elements.length >= 1){
var elCounter = document.getElementById("counter");
for(var i = 0; i < elements.length; i++) {
elements[i] === child ? elements[i].classList.toggle("lineThrough"):null;
}
}
})
var date = new Date().toLocaleDateString("en-US")
footer.innerHTML = date
console.log(date)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Practise App</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="message"class=""></div>
<ul id="uList"></ul>
<button id="btn" type="button" name="button">click here to add items</button><br>
<input id="input" type="text" name="" value="">
<div id="counter" class=""></div>
<footer></footer>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
I don't see findDuplicates being called anywhere.
Also you should prolly call document.getElementsByTagName("li") every time you enter createListItems or findDuplicates to reflect changes you made in html (added li tags).

How to make the script work in a program with html and java?

The script doesn't seem to be working when I'm running my code on sublime.On the contrary, when I run it in fiddle it does work. Here is the https://jsfiddle.net/m5wbdtLg/ . I can't append the question and dropdown in sublime while it is working fine on fiddle. I'm new to this, please help me out. Thank you.
I have tried including resources like this [How to make javascript function active in html
I have also tried $(document).ready(function(){..}); & <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
$( "#add" ).click(function()
{var newElement = '<div class="container"><form id ="ques"><label>Question:</label><br><textarea rows="5" cols="50" name="description" placeholder="Enter a question"></textarea><br><select name="choice" id="choice" onchange="selectorchecker(this)"><option value="">Select choices</option><option value="checkbox">Checkbox</option><option value="radiobtn">Radio Button</option></select></form>';
$( "#ques" ).append( $(newElement) );
});
function selectorchecker(sel) {
document.getElementById("chkbox_choice").style.display = "none";
document.getElementById("rdbtn_choice").style.display = "none";if (sel.value) {
var show = sel.value=="checkbox"?"chkbox_choice":"rdbtn_choice";
document.getElementById(show).style.display = "block";
}
}
function addRowchk(tableID) {
var table_chk = document.getElementById(tableID);
var rowCount_chk = table_chk.rows.length;
var row_chk = table_chk.insertRow(rowCount_chk);
var cell1_chk = row_chk.insertCell(0);
var element1_chk = document.createElement("input");
element1_chk.type = "checkbox";
element1_chk.name="chkbox[]";
cell1_chk.appendChild(element1_chk);
var cell2_chk= row_chk.insertCell(1);
var element2_chk = document.createElement("input");
element2_chk.type = "text";
element2_chk.name = "txtbox[]";
cell2_chk.appendChild(element2_chk);
}
function deleteRowchk(tableID) {
try {
var table_chk = document.getElementById(tableID);
var rowCount_chk = table_chk.rows.length;
for(var i=0; i<rowCount_chk; i++) {
var row_chk = table_chk.rows[i];
var chkbox = row_chk.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table_chk.deleteRow(i);
rowCount_chk--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function addRowRd(tableID) {
var table_rd = document.getElementById(tableID);
var rowCount_rd = table_rd.rows.length;
var row_rd = table_rd.insertRow(rowCount_rd);
var cell1_rd = row_rd.insertCell(0);
var element1_rd = document.createElement("input");
element1_rd.type = "radio";
element1_rd.name="rdbtn[]";
cell1_rd.appendChild(element1_rd);
var cell2_rd= row_rd.insertCell(1);
var element2_rd= document.createElement("input");
element2_rd.type = "text";
element2_rd.name = "txtbox[]";
cell2_rd.appendChild(element2_rd);
}
function deleteRowRd(tableID) {
try {
var table_rd = document.getElementById(tableID);
var rowCount_rd = table_rd.rows.length;
for(var i=0; i<rowCount_rd; i++) {
var row_rd = table_rd.rows[i];
var rdbtn = row_rd.cells[0].childNodes[0];
if(null != rdbtn && true == rdbtn.checked) {
table_rd.deleteRow(i);
rowCount_rd--;
i--;
}
}
}catch(e) {
alert(e);
}
}
You randomly use jquery when everything else is vanilla js, why not just use all vanilla js?
document.getElementById("add").addEventListener("click",function(){
document.getElementById("ques").innerHTML += '<div class="container"><form id ="ques"><label>Question:</label><br><textarea rows="5" cols="50" name="description" placeholder="Enter a question"></textarea><br><select name="choice" id="choice" onchange="selectorchecker(this)"><option value="">Select choices</option><option value="checkbox">Checkbox</option><option value="radiobtn">Radio Button</option></select></form>';
});
<button type="button" id="add">ADD</button>
<div id="ques"></div>

Unable to recreate elements by sessionStorage keys

My JS uses a sessionStorage to set keys and attempts to use these keys to recreate some accordions. I have no problem creating the elements via mouseclick, and I can store the keys and value in sessionStorage.
However, when I try to use a loop to find these keys, it doesn't appear to ever initialize. The remaining elements can be created via click, but the elements created before the refresh never load.
Project4values.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Project4</title>
<style type="text/css"></style>
<link href="Project4Values.css" rel="stylesheet" type="text/css">
<script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type = "text/javascript" src = "Project4Values.js"></script>
</head>
<body id = "sixTypes">
<script>
jQuery(function($){
$(document).ready(function(e) {
$('#MenuBar').load('ProjectMenuBar.html');
});
});
</script>
<div id = "MenuBar"> </div>
<h1 class="h1center"> Values </h1>
<input type="button" id = "ClickCount" onClick="numberSection()" value="Click Here">
<p/>
</body>
</html>
Project4Values.css
#charset "utf-8";
/* CSS Document */
.h1center{
text-align:center;
}
input.accordian{
background-color: #501214;
padding: 18px;
width: 100%;
text-align: left;
color: white;
transition: 0.4s;
}
div.panel{
display: none;
}
div.panel.show{
display: block;
}
Prject4Values.js
function numberSection() {
"use strict";
var paraStr = ["Numbers", "Strings", "Booleans", "Functions", "Objects", "Undefined Values"];
var buttonClass = "accordian";
var divClass = "panel";
var button = document.createElement("input");
if (typeof (Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
}
//check for the first key made, then loop through and recreate the elements when the page loads
if (sessionStorage.getItem("containerNumber") !== null) {
window.onload = function () {
var x;
for (x = 0; x < sessionStorage.clickcount || x < 6; x++) {
button.className = buttonClass;
button.type = "button";
button.value = paraStr[x];
alert(button.value);
document.getElementById("sixTypes").appendChild(button);
createAccordian(document.getElementById("sixTypes"), divClass, button.value);
toggleText(buttonClass);
}
};
}
//while there are strings in the array, assign that string to button value
if (sessionStorage.clickcount - 1 < paraStr.length) {
button.className = buttonClass;
button.type = "button";
button.value = paraStr[sessionStorage.clickcount - 1];
document.getElementById("sixTypes").appendChild(button);
createAccordian(document.getElementById("sixTypes"), divClass, button.value);
toggleText(buttonClass);
}
}
function createAccordian(parentElement, strName, strStore) {
"use strict";
var accordian = document.createElement("div");
accordian.className = strName;
buildCellContent(accordian);
parentElement.appendChild(accordian);
sessionStorage.setItem("container" + strStore, strStore); //sets the Item in storage that I want to call later.
return parentElement;
}
function buildCellContent(parentElement) {
"use strict";
var x = sessionStorage.clickcount - 1;
var numText = "This text will go in the numbers section";
var strText = "This text will go in the strings section";
var boolText = "This text will go in the boolean section";
var funText = "This text will go in the function section";
var objText = "This text will go in the objects section";
var undefText = "This text will go in the undefinded section";
var textBlock = [numText, strText, boolText, funText, objText, undefText];
var textNode = document.createTextNode(textBlock[x]);
var pText = document.createElement("P");
pText.appendChild(textNode);
parentElement.appendChild(pText);
return parentElement;
}
function toggleText(cName) {
"use strict";
var acc = document.getElementsByClassName(cName);
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function () {
this.nextElementSibling.classList.toggle("show");
};
}
}

Removing the corresponding textbox of the anchor tag

I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}

How do I delete a record in my javascript to do list?

I'm working on a to do list and I'm trying to create a delete button that will prompt an id number to delete a record. You pick which record you want to delete. Not sure how to go about doing it. This code has the html in it as well.
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<style>
body{margin:20px;}
</style>
<script type="text/javascript">
var list;
var addBtn;
document.addEventListener("DOMContentLoaded",load);
function load(){
list = get("list");
checkboxes = getTag("input");
addBtn = get("addBtn");
addBtn.addEventListener("click",addItem);
for(var i = 0, l = checkboxes.length; i < l ; i++){
if(checkboxes[i].type == "checkbox")
checkboxes[i].addEventListener("click",updatePercent);
}
if(localStorage.listFile)
//list.innerHTML = localStorage.listFile;
updatePercent();
}
function updatePercent(){
var checkboxes = getTag("input");
var total = checkboxes.length/2;
var done = 0;
for(var i = 0, l = checkboxes.length; i < l ; i++){
if(checkboxes[i].checked)
done++;
}
get("percentage").innerHTML = "Done: " + Math.round((done/total)*100) + "%";
}
function addItem(){
var item = document.createElement('li');
var chk = document.createElement("input");
var txt = document.createElement("input");
chk.type = "checkbox";
txt.type = "text";
chk.addEventListener("click",updatePercent);
item.appendChild(chk);
item.appendChild(txt);
list.appendChild(item);
updatePercent();
}
function get(id){
return document.getElementById(id);
}
function getTag(tag){
return document.getElementsByTagName(tag);
}
function save(){
localStorage.listFile = list.innerHTML;
}
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
//checkboxes[i].splice(i,1);
checkboxes[i].innerHTML = "";
}
</script>
</head>
<body>
<h1>Kung Fu To Do List 1.0</h1>
<ol id="list">
<li><input type="checkbox"><input type="text"></li>
</ol>
<p id="percentage"></p>
<button id="addBtn">Add Item</button><button onclick="save()">Save</button><button onclick="deleteTsk()">Delete</button>
</body>
I figured out how to delete it with this method.
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
var item = getTag("li");
list.removeChild(item[i]);
}
I figured out how to delete it with this method.
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
var item = getTag("li");
list.removeChild(item[i]);
}

Categories