I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.
This is my basic HTML structure:
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
This is what I want to add inside the content div:
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow()">
You can do something like this.
function addRow() {
const div = document.createElement('div');
div.className = 'row';
div.innerHTML = `
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label>
<input type="checkbox" name="check" value="1" /> Checked?
</label>
<input type="button" value="-" onclick="removeRow(this)" />
`;
document.getElementById('content').appendChild(div);
}
function removeRow(input) {
document.getElementById('content').removeChild(input.parentNode);
}
To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).
So using it you would write
function addRow () {
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
`<div class="row">
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
Another solution is to use getDocumentById and insertAdjacentHTML.
Code:
function addRow() {
const div = document.getElementById('content');
div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');
}
Check here, for more details:
Element.insertAdjacentHTML()
I know it took too long, it means you can write more briefly.
function addRow() {
var inputName, inputValue, label, checkBox, checked, inputDecrease, content, Ptag;
// div
content = document.getElementById('content');
// P tag
Ptag = document.createElement('p');
// first input
inputName = document.createElement('input');
inputName.type = 'text';
inputName.name = 'name';
// Second input
inputValue = document.createElement('input');
inputValue.type = 'text';
inputValue.name = 'Value';
// Label
label = document.createElement('label');
// checkBox
checkBox = document.createElement('input');
checkBox.type = 'checkbox';
checkBox.name = 'check';
checkBox.value = '1';
// Checked?
checked = document.createTextNode('Checked?');
// inputDecrease
inputDecrease = document.createElement('input');
inputDecrease.type = 'button';
inputDecrease.value = '-';
inputDecrease.setAttribute('onclick', 'removeRow(this)')
// Put in each other
label.appendChild(checkBox);
label.appendChild(checked);
Ptag.appendChild(inputName);
Ptag.appendChild(inputValue);
Ptag.appendChild(label);
Ptag.appendChild(inputDecrease);
content.appendChild(Ptag);
}
function removeRow(input) {
input.parentNode.remove()
}
* {
margin: 3px 5px;
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
To remove node you can try this solution it helped me.
var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);
Add HTML inside div using JavaScript
Syntax:
element.innerHTML += "additional HTML code"
or
element.innerHTML = element.innerHTML + "additional HTML code"
Remove HTML inside div using JavaScript
elementChild.remove();
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
<!DOCTYPE html>
<html>
<head>
<title>Dynamical Add/Remove Text Box</title>
<script language="javascript">
localStorage.i = Number(1);
function myevent(action)
{
var i = Number(localStorage.i);
var div = document.createElement('div');
if(action.id == "add")
{
localStorage.i = Number(localStorage.i) + Number(1);
var id = i;
div.id = id;
div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';
document.getElementById('AddDel').appendChild(div);
}
else
{
var element = document.getElementById(action.id);
element.parentNode.removeChild(element);
}
}
</script>
</head>
<body>
<fieldset>
<legend>Dynamical Add / Remove Text Box</legend>
<form>
<div id="AddDel">
Default TextBox:
<input type="text" name="default_tb">
<input type="button" id="add" onclick="myevent(this)" value="Add" />
</div>
<input type="button" type="submit" value="Submit Data" />
</form>
</fieldset>
</body>
</html>
Related
I'm working on a TO DO List.
here's the HTML body-
<div class="cardDiv">
<input type="text" class="titleText" placeholder="Today's Battle Plans🤠">
<div class="taskList">
<div class="indiv-task task1">
<input type="checkbox" class="checkBox">
<input type="text" class="textBox" placeholder="task1">
</div>
</div>
<button class="addTask-btn" onclick="addTask()">Add More Tasks</button>
</div>
<script src="index.js"></script>
Basically, the button at the end adds a code block for a new task each time the button gets pressed as per this JS code-
let taskList = document.querySelector(".taskList");
let taskCode = '<div class="indiv-task"> <input type="checkbox" class="checkBox"> <input type="text" class="textBox" placeholder="task1"> </div>';
function addTask() {
taskList.innerHTML += taskCode;
let taskListLength = document.querySelectorAll(".indiv-task").length;
for(i=0; i<taskListLength; i++) {
document.querySelectorAll(".textBox")[i].placeholder = "task"+(i+1);
document.querySelectorAll(".indiv-task")[i].classList.add("task"+(i+1));
}
}
But the problem is that whenever the button is pressed all the input text in textBox(es) gets erased. Is there a way I can avoid that, or is it possible only with databases?
PS- I'm still on my learning path...
Like what epascarello said we need to create an element and add it to the taskList element and not use innerHTML to add elements.
let taskList = document.querySelector(".taskList");
let taskHTML = '<input type="checkbox" class="checkBox"> <input type="text" class="textBox" placeholder="task1">';
function addTask() {
let taskCode = document.createElement("DIV");
taskCode.innerHTML = taskHTML;
taskCode.classList.add("indiv-task")
taskList.appendChild(taskCode)
let taskListLength = document.querySelectorAll(".indiv-task").length;
for(i=0; i<taskListLength; i++) {
document.querySelectorAll(".textBox")[i].placeholder = "task"+(i+1);
document.querySelectorAll(".indiv-task")[i].classList.add("task"+(i+1));
}
}
This means that the innerHTML for the taskList element is not reset to have empty text boxes, rather, it just adds another element.
This is because the innerHTML will replace the current html of the element. You can try with:
function addTask() {
const taskList = document.querySelector(".taskList");
const taskCode = '<div class="indiv-task"> <input type="checkbox" class="checkBox"> <input type="text" class="textBox" placeholder="task1"> </div>';
const taskCodeDocument = new DOMParser().parseFromString(taskCode, "text/html");
const taskCodeChild = taskCodeDocument.body.firstChild;
taskList.appendChild(taskCodeChild);
let taskListLength = document.querySelectorAll(".indiv-task").length;
for (i = 0; i < taskListLength; i++) {
document.querySelectorAll(".textBox")[i].placeholder = "task" + (i + 1);
document.querySelectorAll(".indiv-task")[i].classList.add("task" + (i + 1));
}
}
ref: https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString
& https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
this is my code but add button is coming of first field but i want that whenever a new input field came the add button shift next to the new input field.
function add(){
var new_chq_no = parseInt($('#total_chq').val())+1;
var new_input="<input type='text' id='new_"+new_chq_no+"'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no)
}
function remove(){
var last_chq_no = $('#total_chq').val();
if(last_chq_no>1){
$('#new_'+last_chq_no).remove();
$('#total_chq').val(last_chq_no-1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
Try This
var new_id = 0;
function add() {
new_id += 1;
var inp_div = document.getElementById("inputs");
var new_inp = document.createElement("input");
new_inp.setAttribute("id", new_id);
inp_div.appendChild(new_inp);
}
function remove() {
if (new_id >= 1) {
document.getElementById(new_id).remove();
new_id -= 1;
}
}
<div id="inputs">
<input type="text">
</div>
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
Try wrapping the button and the input in a div with css attribute display: inline-block
How do I make this calculator display the result on the first page after the ='s sign without destroying all of the html on the page with document.write()?
I know that document.write() is the problem, but I don't know of anything else to use. I'm very new to coding, so any help is greatly appreciated.
I also have a problem with the division part because it is putting the result right next to the remainder, however, once the document.write() problem is resolved, I think that the solution should become more apparent. Thank You!
<head>
<script language="javascript" type="text/javascript">
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.write(result);
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.write(result)
document.write(remainder)
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.write(result);
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.write(result);
}
</script>
<title>java</title>
</head>
<body>
Addition
<p>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
</p>
<p>
Subtraction
<p>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<p>Multiplication
<p>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
</p>
<p>Division
<p>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
</p>
</body>
</html>
You can either use textContent or innerHTML.
Here's an example using textContent:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').textContent = result;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').textContent = result;
document.getElementById('divide-remainder').textContent = remainder;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').textContent = result;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').textContent = result;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
With textContent you can only set text, with innerHTML you can set HTML:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').innerHTML = `<i style="color: blue">${result}</i>`;
document.getElementById('divide-remainder').innerHTML = `<i style="color: blue">${remainder}</i>`;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
It's worth noting, with innerHTML there are security concerns as mentioned here:
...there are ways to execute JavaScript without using elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use Node.textContent. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
Here are some other methods used to manipulate the DOM:
insertAdjacentElement
innerText
insertAdjacentHTML
insertAdjacentText
insertBefore
appendChild
replaceChild
removeChild
nodeValue
outerHTML
outerText
remove
See the full list here.
As you have discovered, document.write() is tricky because it has a tendency to overwrite the existing content when used. Let's see what the documentation has to say about it:
Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.
Hmm, well what else can we do? Fortunately, it is possible to target specific parts of the page and replace content in those elements only. So, for example we could add <span> elements with ids like #add-result, #div-result etc to the page which will contain the results of their respective action. Then, instead of using document.write() to output the results, we can replace the content in those elements.
Let's add a <span> to contain our add result:
Addition<p>
<input type="text" id="t1" name="t1" /> +
<input type="text" id="t2" name="t2" />
<input type="button" id="add" value="=" onClick="add();" />
<span id="add-result></span>
</p>
(Note: remember to close your <input /> tags with a />!)
How do we target a specific element? With document.querySelector(). Docs
Then, we can easily change the content inside of that element by updating the element.textContent property, just like you would a variable:
function add(){
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1+input2;
// get the element with the #add-result ID
var element = document.querySelector("#add-result");
// update the content in that element
element.textContent = result;
}
Now when you add two numbers together and press =, the result will appear inside of the <span id="add-result"></span> element instead of overwriting the entire page. See if you can get it working for the other inputs as well. Remember you will need a unique id for each element you want to display a result in, and update the calculation functions accordingly!
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
I have a dynamically created table that I am using with DataTables and TableTools - it works great except I have an input textbox that I need to get the value out of when clicking a button, but it just gives me the html, e.g.
<input size="3" type="text">
I have created a DataTables live to try and recreate the issue, but bizarrely the html returned on there gives the value where it doesn't for me (in the html but still, at least I could parse that) - it still doesn't give you the right value though if you change the Quantity - see here http://live.datatables.net/bidetoku/1/
This is how the table is created:
var tr = [];
var sorTable = document.getElementById('tblSORS');
for (var i = 0; i < sorresults.length; i++) {
tr[i] = document.createElement('tr');
var tdsorID = document.createElement('td');
var tdCode = document.createElement('td');
var tdDesc = document.createElement('td');
var tdClient = document.createElement('td');
var tdCreated = document.createElement('td');
var tdQuantity = document.createElement('td');
var inputQty = document.createElement('input');
inputQty.type = "text";
inputQty.value = "1";
inputQty.size = "3";
tdsorID.appendChild(document.createTextNode(sorresults[i].selectSingleNode('./itt_scheduleofratesid').nodeTypedValue));
tdCode.appendChild(document.createTextNode(sorresults[i].selectSingleNode('./itt_code').nodeTypedValue));
tdDesc.appendChild(document.createTextNode(sorresults[i].selectSingleNode('./itt_description').nodeTypedValue));
tdClient.appendChild(document.createTextNode(sorresults[i].selectSingleNode('./itt_clientcontractid.itt_description').nodeTypedValue));
tdQuantity.appendChild(inputQty);
tdCreated.appendChild(document.createTextNode(returnDate(sorresults[i].selectSingleNode('./createdon').nodeTypedValue)));
tr[i].appendChild(tdsorID);
tr[i].appendChild(tdCode);
tr[i].appendChild(tdDesc);
tr[i].appendChild(tdClient);
tr[i].appendChild(tdQuantity);
tr[i].appendChild(tdCreated);
sorTable.getElementsByTagName('tbody')[0].appendChild(tr[i]);
}
var sors = $('#tblSORS').DataTable({
"destroy": true,
"info": false,
"lengthChange": true,
dom: 'T<"clear">lfrtip',
tableTools: {
"sRowSelect": "multi",
"aButtons": ""
}
});
// hide scheduleofratesid column
sors.column(0).visible(false);
Any help would be great, been struggling with this for a while now.
Edit: Here is some code that seemed to half do what I wanted but not completely
function getQuantity(){
var table = $('#example').dataTable();
var data = table.$('input').serialize();
var oTT = $.fn.dataTable.TableTools.fnGetInstance('example');
var rows = oTT.fnGetSelectedData();
if (rows.length > 0) {
var selectedRows = oTT.fnGetSelectedIndexes();
selectedRows.forEach(function (i) {
alert(document.getElementById('example')
.rows[i]
.cells[0]
.firstChild
.value
);
});
}
}
This is a jQuery that might help you:
$(".test").each(function () {
//Example: add a click event for every item that has the class .test
$(this).click(function (){
//This will get you the value from the clicked element
valueOfElement = $(this).val();
});
});
However you might have to add a common class for all those imputs.
jQuery reference https://api.jquery.com/each/
Try the next code:
<!doctype html>
<html lang="es">
<head>
<title>Stack Overflow</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#simpleButton").click(function(){
$(".fields").each(function () {
value = $(this).val();
alert(value);
});
});
});
</script>
</head>
<body>
<div id="texts">
<input type="text" size="25" value="1" class="fields">
<br/>
<input type="text" size="25" value="2" class="fields">
<br/>
<input type="text" size="25" value="3" class="fields">
<br/>
<input type="text" size="25" value="4" class="fields">
<br/>
<input type="text" size="25" value="5" class="fields">
<br/>
<input type="button" value="Get the values" id="simpleButton">
</div>
</body></html>