Changing input values after row has been removed - javascript

I'm trying to create a tool where the user clicks on a button and it adds a label,input and remove button. I have it all working for the most part but there is only couple things missing. If the user had let's say adds "4" items and he/she deleted item "2"; I want the label value to subtract
"-1" of its value and the id of that item to subtract "-1" of its value. Any help would be appreciated!
I have created a jsFiddle below:
http://jsfiddle.net/ryanverdel/fUhL8/
HTML
<input type="input" value="0" id="theValue" />
<div id="myDiv">
</div>
Javascript
function addItem() {
if ($('#theValue').val() < 10){
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('form');
var newlabel = document.createElement('input');
var newinput = document.createElement('input');
var newbutton = document.createElement('input');
var divIdName = 'Address'+num;
newdiv.setAttribute('id',divIdName);
newbutton.setAttribute('type','button');
newbutton.setAttribute('onclick','onclick=confirmDelete("'+divIdName+'"); return false;');
newbutton.setAttribute('value','Delete');
//newlabel.innerHTML ='Address('+num+')';
newlabel.setAttribute('value','Address '+num+':')
newlabel.setAttribute('size','8');
newlabel.setAttribute('class','label');
newlabel.setAttribute('readonly','true');
newinput.setAttribute('type','text');
newinput.setAttribute('id',divIdName+'_input');
ni.appendChild(newdiv);
newdiv.appendChild(newlabel);
newdiv.appendChild(newinput);
newdiv.appendChild(newbutton);
}
else{
return false;
};
}
function confirmDelete(divNum){
if (confirm("Are you sure you want to delete " +divNum+"?"))
{
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
var getLabel = olddiv.getElementsByClassName("label");
var counter= $('#theValue').val();
$('#theValue').val( (counter-1<0)?counter:--counter );
//$(getLabel).nextAll().css( "color", "red" );
$(olddiv).nextAll().css('background-color', 'red').css('color','red');
d.removeChild(olddiv);
}
else{};
}

Related

HTML Javascript dynamically add and remove textboxes

I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}

Using onclick in javascript to create a new div inside a div created using onclick itself?

I created a div consisting of radio button inputs using onclick from a radio button input inside a form in php and then i again attempted to create another div using onclick from inside this created div but only the outer div is being created. Would like to know where i am wrong..
<input id="sub" type="radio" name="opt1" value="2" onclick="createDiv4()"> Academic User<br/>
function createDiv4() {
if(document.getElementById("acad_")==null)
{
var divi = document.createElement("div");
divi.id="acad_";
divi.style.height="100px";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.onclick="createDiv4_1()";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("Technical Institute");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
ip2.onclick="createDiv4_1()";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("School");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("acad_");
divi1.parentNode.removeChild(divi1);
}
}
</script>
<script>
function createDiv4_1() {
if(document.getElementById("school")==null)
{
var divi = document.createElement("div");
divi.id="school";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User for Workshop :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("School Student");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("Teacher");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
var b2 = document.createElement("BR");
divi.appendChild(b2);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe3 = document.createElement("label");
var labe_val3 = document.createTextNode("Parent");
labe3.appendChild(labe_val3);
divi.appendChild(labe3);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("school");
divi1.parentNode.removeChild(divi1);
}
}
</script>
You arent calling the functions properly. Instead of :
ip.onclick= "createDiv4_1()";
This is only a string, it won't call it. You put it in quotes in the HTML but in JavaScript you don't need to. Also get rid of the parenthesis in JS. So use this :
ip.onclick= createDiv4_1;
Working fiddle : https://jsfiddle.net/thatOneGuy/xgvqwcq4/2/
I added a div with ID contain for this to work too.
according to your question title you have two option.
forget about onclikc inside the html and use normal js
document.getElementById("secondDiv").addEventListener("click", function () {
newFunctionI();
})
/*JQ version*/
$("#secondDiv").on("click", function () {
newFunctionI();
})
second way is: use jquery append() or html();
function yourFunctionI() {
$("#ID").append("<div id='secondDiv' onclick='newFunction()'> new </div>")
}

todo list- trying to add inputs to an array/doesnt work

I am building a small todo list and want to do the following: each text input (or actually a copy of the text input) should be added to an empty string (copy because it should not disappear when added). Then I have a function which is called when user clicks on a button and then I want to pick a random todo thing.
I didn't even get to the point when I pick out a random todo thing because my code just doesn't work- It seems like the adding does happen, but instead of adding a todo thing, thats being added:[object HTMLInputElement]
Anyone has an idea?
My javascript code:
var totalItems=0;
var listOf="";
function randomItem(){
document.getElementById("randomArray").innerHTML=listOf;
}
function updatingItem() {
var cbId = this.id.replace("cb_", "");
var textItem = document.getElementById("item_" + cbId);
if (this.checked) {
textItem.style.textDecoration = "line-through";
textItem.style.background="pink";
}
else {
textItem.style.textDecoration = "none";
textItem.style.background="white";
}
}
function addItem() {
totalItems++;
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "cb_" + totalItems;
checkBox.onclick = updatingItem;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.innerHtml = textItem;
var textItem = document.getElementById("textItem");
span.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
var listOfItems=textItem;
listOf+=listOfItems;
}
var item = document.getElementById("add");
item.onclick = addItem;
document.getElementById("lastButton").onclick=randomItem;
HTML:
<body>
<div class="table">
<h1>To Do List</h1>
</div>
<p>
<input type="text" id="textItem"/>
<button id="add"><b>Add</b></button>
</p>
<ul id="todoList"></ul>
<h3>Pick a random to do thing to do for today</h3>
<button id="lastButton">Go!</button>
<p id="randomArray"></p>
</body>
Your randomItem() function is working incorrectly, as you are trying to create String from Object directly while using listOfItems. Either use its value or try using following code instead for proper view. Also add one list element in HTML with id="myList". IT will work fine.
JS:
function randomItem(){
var counter = 0;
var textItems = document.getElementsByTagName("input");
var done = [];
for (var i=0; i<textItems.length; i++)
{
if(textItems[i].type == "checkbox")
{
if(textItems[i].checked)
{
document.getElementById("item_"+i);
done.push(document.getElementById("item_"+i).innerHTML);
var list = document.getElementById('myList');
var data = document.createElement('li');
data.appendChild(document.createTextNode(done[counter]));
counter++;
list.appendChild(data);
}
}
}
}
HTML:
<ol id = "myList"></ol>
try
var listOfItems=textItem.value;
rather than
var listOfItems=textItem;

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);
}
}

Javascript -> Attempting to dynamically add radio buttons from an array

So I'm working on my very first 'real' JavaScript project -> the famed Quiz app :)
I'm passing questions and answers via an array, and I want make sure to allow for a variable number of answer options. To do this, I'm using a For loop and the createElement method to add and populate the appropriate HTML for each answer in the array. To my eyes, what I've built actually works great. And after running the function I can see the resultant HTML elements in the right place and with all the appropriate tagging in my console. However, the inner DIV text won't render on screen! Very confused. What am I missing? Please help!
My JS code:
<body>
<form id="form1">
</form>
<script>
var answers = ["answer1", "answer2", "answer3", "answer4", "answer5"];
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("form1");
for (var i = 0; i < len; i++){
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
form.appendChild(radio);
radio.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
}
}
</script>
</body>
And here's a screenshot of my console AFTER I run the function, for reference:
You're plan is nearly working but Input elements have no content! So the div's will not be rendered at all!
Create a div that contains your radio button and the input text on the same level:
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
radioText.innerHTML = array[i];
radioText.appendChild(radio);
form.appendChild(radioText);
Add label after or before radio button. Label will let you check radio button by clicking on it's text
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("label");
radioText.id = "c" + i;
radioText.setAttribute("for", "choice" + i);
radioText.class = "choiceText";
form.appendChild(radio);
form.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
<input> cannot contain any DOM elements or DOM nodes. But if you want to have checkboxes associated with some text, I suggest you to use <input> with <label for=""> where label.for is name of input element. For combining them you can put them into some container(i.e. <div>):
By default on label with set property for raises click event on element with the same name property value as for property value. This means that you do not need to add additional click event handlers for <label> elements.
var checkId = 1;
var container = document.createElement("div");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices"+checkId;
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var label = document.createElement("label");
label.innerHTML = array[i];
// Set attribute for
label.setAttribute("for","choices"+checkId);
//Increase counter for check element name.
checkId++;
container.appendChild(radio);
container.appendChild(label);
form.appendChild(container);

Categories