Add JQuery functionality to dynamically created radio buttons - javascript

I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!

Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});

Related

To do list javascript-something is wrong with my code/order

I'm building a small to do list and everything worked fine so far until I included a checkbox. now when I click on the button, nothing happens and neither do I see a checkbox. There must be something wrong with the order of code-does someone know how I need to rearrange the code and WHY?
Html code:
<body>
<h1>To Do List</h1>
<p><input type="text" id="textItem"/><button id="add">Add</button></p>
<ul id="todoList">
</ul>
</body>
Javascript code:
function addItem() {
var entry = document.createElement("li");
var checkBox = document.getElementById("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
var item = document.getElementById("add");
item.onclick = addItem;
UPDATED - I've spotted 4 issues . Follow Below :
1st : When you create the check box you should be using setAttribute method to specify input type : checkbox.setAttribute("type" , "checkbox")
2nd : Your checkbox variable should be creating an input element : var checkBox = document.createElement("input");
3rd : You should be using innerHtml instead of innerText as you are referencing a list ELEMENT stored in your entry variable : span.innerHtml = entry;
4th: Really minor but you should grab your item and attach an event to the item before your function :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
Just change your javascript to the following :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
function addItem() {
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.setAttribute("type" , "checkbox");
var span = document.createElement("span");
span.innerHtml = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
Example Here : http://codepen.io/theConstructor/pen/pyPdgg
Good Luck!

how to create dynamic grid using javascript

s.no. | description
abcd1
abcd2
abcd3
i want to add more rows through input. now what i want is when i will add another row. let say {describtion="abcd4"}
then the above grid will become
s.no. | description
abcd4
abcd1
abcd2
abcd3
meaning s.no. field got updated and new row will be added at top. adding a new row on top is no issue but how could i update s.no. at same time, here i want to ask is there any specific way to do this.
Here is a solution that adds rows at the top of a table and keeps the numbers updated:
document.querySelector('#btnadd').addEventListener('click', function () {
var inp = document.querySelector('#inpadd');
var descr = inp.value;
if (descr === '') return; // do not add empty values
var grid = document.querySelector('#grid');
// first increment all row numbers
for (var i = 1, row; row = grid.rows[i]; i++) {
row.cells[0].textContent = i+1;
}
// add new row
var row = grid.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.textContent = 1;
cell2.textContent = descr;
// clear input
inp.value = "";
});
New description: <input type="text" id="inpadd"><button id="btnadd">Add</button>
<table id="grid">
<tr><th>s.no.</th><th>description</th></tr>
<table>
If you want to insert new text description in the beginning of the ordered list, you can use 'insertBefore' javascript code:
list.insertBefore(entry, list.firstChild);
It should add the new text in the beginning of the list. Refer below code if it helps your problem.
<!DOCTYPE html>
<html>
<body>
<p>Input the text description and click 'Add Description' button to insert in list:</p>
<form>
Description Text:<br>
<input type="text" name="description" id="description">
<br>
<input type="button" value="Add Description" onclick='appendDescription()'>
</form>
<ol id="desclist">
<li>abcd1</li>
<li>abcd2</li>
<li>abcd3</li>
</ol>
<script>
function appendDescription(){
var description= document.getElementById('description').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(description));
var list = document.getElementById('desclist');
list.insertBefore(entry, list.firstChild);
}
</script>
</body>
</html>
function pushAtStarting(array, element){
array.unshift(element); // new element has s.no = 0
for (index in array){
array[index].sno++
}
}
var array = [];
pushAtStarting(array, {sno: 0, description: "abc"});
it works if your grid is java script arrays and elements are json elements.

Removing items from a to do list using Javascript

Attempting my first Javascript project, playing around with DOM to make a To-Do List.
After adding an item, how do i get the 'Remove' button to function and remove the item + the remove button.
Furthermore, after a new entry is made, the list item still stays in the input field after being added. How can it be made to be blank after each list item.
And yes i know my code is kinda messy and there is most likely an easier way to create it but I understand it like this for now.
Any help is greatly appreciated. Thanks
JSFiddle Link : http://jsfiddle.net/Renay/g79ssyqv/3/
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
node.appendChild(removeTask);
}
You can simply assign event:
removeTask.addEventListener('click', function(e) {
node.parentNode.removeChild(node);
});
http://jsfiddle.net/g79ssyqv/6/
Edited the Fiddle... just try this
FiddleLink (Should work now, button and p-tag will be removed)
HTML
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
JS
var row = 0;
function addText(){
var input = document.getElementById('inputTask').value;
if(input != "")
{
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
node.setAttribute("id","contentP"+row);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.setAttribute("onClick", "deleterow("+ row +");");
node.appendChild(removeTask);
row++;
}
else
{
alert("Please insert a value!");
}
}
function deleterow(ID)
{
document.getElementById('contentP'+ID).remove();
}
Greetings from Vienna
Use this
// +your code
.....
node.appendChild(removeTask);
// + modify
removeTask.onclick = function(e){
var dom = this;
var p_dom = this.parentNode;
console.log(p_dom);
var parent_node = p_dom.parentNode;
parent_node.removeChild(p_dom);
}

Input field not appending to td

I am trying to create a table with an input field dynamically but my code ends up creating an empty table.
var calcDiv = document.getElementById("calc_div");
var calcTab = document.createElement('TABLE');
var tbody = document.createElement('TBODY');
var calcForm = document.createElement('FORM');
calcForm.id = "calculator_form";
//calc display
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.colspan = "4";
var comp = document.createElement('INPUT');
comp.type = "text";
comp.value = 0;
comp.disabled = true;
comp.id = "compDisplay";
td.appendChild(comp); //THIS DOESN'T SEEM TO WORK
tr.appendChild(td);
tbody.appendChild(tr);
calcForm.appendChild(comp);
calcTab.appendChild(tbody);
calcTab.style.width = "500px";
calcTab.style.height = "500px";
calcDiv.appendChild(calcTab);
You were missing a line and were incorrectly appending another. In:
tr.appendChild(td);
tbody.appendChild(tr);
calcForm.appendChild(comp);
You needed to:
tr.appendChild(td);
tbody.appendChild(tr);
calcTab.appendChild(tbody); <-- append the tbody to the table
calcForm.appendChild(calcTab); <-- append the table to the form
jsFiddle example
This produces the HTML:
<div id="calc_div">
<table style="width: 500px; height: 500px;">
<tbody>
<tr>
<td>
<input type="text" disabled="" id="compDisplay">
</td>
</tr>
</tbody>
</table>
</div>
Note that you may also want to use td.setAttribute('colspan','4'); instead of td.colspan = "4";
Maybe because you are adding the input named "comp" again in the form after two rows? "calcField.addChild(comp)"
What's happening is you're appending comp to the td, then appending it to the form after that. This removes it from the table it was in and puts it in the form, which isn't attached anywhere in your document.
Here's a sample with the appending to the form commented out. Or perhaps you'd prefer to append the form to the td instead.
I think this method will help you out. I've coded it so that the appendChild follows the DOM tree. Take a look. Note: I created a variable to append the target "calc_div" to the document body. Feel free to take that out.
var div = document.body.appendChild(document.createElement('div'));
div.id = "calc_div";
var table = div.appendChild(document.createElement('table'));
table.style.width = "500px";
table.style.height = "500px";
var tbody = table.appendChild(document.createElement('tbody'));
var trow = tbody.appendChild(document.createElement('tr'));
var tcell = trow.appendChild(document.createElement('td'));
tcell.colSpan = "4";
var input = tcell.appendChild(document.createElement('input'));
input.id = "compDisplay";
input.type = "text";
input.value = 0;
input.disabled = true;

Javascript button with css

EDIT:
Currently using this javascript code, it works for the plus box but not the minus. (changed code fragment from the below.
// Create buttons for creating and removing inputs
var newAddButton = document.createElement('input');
newAddButton.id= "submit2";
newAddButton.type = "button";
newAddButton.value = " + ";
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = " - ";
newAddButton.id= "submit2";
I've got a javascript form, two buttons and a form is created when the plus is clicked, I was just wondering if the buttons that appear can be set to the same CSS style as the button next to the drop down lists.
So in short a css style attached to the buttons made through a javascript
HTML
<div id="mainContainer">
<div>
<select name="text[]">
<option value="t1">t1</option>
<option value="t2">t2</option>
<option value="t3">t3</option>
</select>
<input name="none" type="button" id="submit2" onClick="addNew();" value=" + ">
</div>
</div>
JAVASCRIPT
var counter = 0;
function addNew(e) {
var countAll = document.getElementsByTagName("select").length - 1;
var lastSelectBox = document.getElementsByTagName("select")[countAll];
var items = lastSelectBox.innerHTML;
// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');
// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');
// Create a new text input
var newText = document.createElement('select');
newText.type = "select";
newText.setAttribute("name", "text[]");
newText.innerHTML = items;
//for testing
// Create buttons for creating and removing inputs
var newAddButton = document.createElement('input');
newAddButton.type = "button";
newAddButton.value = " + ";
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = " - ";
// Append new text input to the newDiv
newDiv.appendChild(newText);
// Append new button inputs to the newDiv
newDiv.appendChild(newAddButton);
newDiv.appendChild(newDelButton);
// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);
// Add a handler to button for deleting the newDiv from the mainContainer
newAddButton.onclick = addNew;
newDelButton.onclick = function() {
mainContainer.removeChild(newDiv);
};
};
There are a number of things wrong with the fiddle.
To get your question out of the way, the CSS has an extraneous }, which causes the style for #submit3 to be ignored. Remove it.
The Javascript in the fiddle should not be wrapped in an onload handler; set it to "No wrap - in head" or "No wrap - in body". Otherwise clicking the button won't work.
The newly created buttons all have the same IDS. This is a no-no. Make the Javascript remember how many buttons there are and give them a unique ID based on the count. (Something like ++numberofbuttons; id = 'submit'+(numberofbuttons*2); for the one, and same plus +1 for the other.)
Oh, and your fiddle differs from the example code in the question. Don't do that.

Categories