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>
Related
I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>
In the code below it works great to clone the table, but it doesn't go deep enough to rename the inputs of each form field in the table. For example Attendee1, Attendee2, Attendee3 etc.
Is there a way instead of just grabbing NewEl.children a way to just find all the input elements within the table then rename them?
I am not trying to add a row, I need to clone the entire table.
Any help you all out there in cyberland can give will be greatly appreciated.
<form name="EditRoster" method="post" action="DoRoster.php">
<table id="RosterTbl" cellspacing="0" cellpadding="2">
<tr style="text-align:left;vertical-align:top;">
<td><b>Name</b>:</td>
<td>
<input type="text" name="Attendee" value="" size="25" onclick="alert(this.name)">
</td>
<td><b>Paid</b>:</td>
<td>
<input type="checkbox" name="Paid" value="Yes" size="25">
</td>
</tr>
<tr style="text-align:left;vertical-align:top;">
<td><b>Email</b>:</td>
<td>
<input type="text" name="Email" value="" size="25">
</td>
<td><b>Paid When</b>:</td>
<td>
<input type="text" name="PaidWhen" value="" size="10">
</td>
</tr>
</table>
<div style="padding:5px;">
<input type="hidden" name="NumStudents" value="0">
<input type="button" name="AddPersonButton" value="Add Person" onclick="CloneElement('RosterTbl','NumStudents');">
</div>
</form>
<script language="javascript">
var TheForm = document.forms.EditRoster;
function CloneElement(ElToCloneId, CounterEl) {
var CloneCount = TheForm[CounterEl].value;
CloneCount++;
TheForm[CounterEl].value = CloneCount;
var ElToClone = document.getElementById(ElToCloneId);
var NewEl = ElToClone.cloneNode(true);
NewEl.id = ElToCloneId + CloneCount;
NewEl.style.display = "block";
var NewField = NewEl.children;
for (var i = 0; i < NewField.length; i++) {
var InputName = NewField[i].name;
if (InputName) {
NewField[i].name = InputName + CloneCount;
}
var insertHere = document.getElementById(ElToCloneId);
insertHere.parentNode.insertBefore(NewEl, insertHere);
}
}
</script>
Looked like you were on the right track, but I think you were taking a few extra steps, so I think I simplified it ;)
One thing you were missing was that the value of NumStudents is returned as a string so you have to call parseInt() on it.
var theForm = document.forms.EditRoster;
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function CloneElement(cloneID, counterName) {
var clone = document.getElementById(cloneID);
var newClone = clone.cloneNode(true);
var counter = theForm[counterName].value = parseInt(theForm[counterName].value) + 1;
// Update the form ID
newClone.id = newClone.id + counter;
// Update the child Names
var items = newClone.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
if (items[i].name != null)
items[i].name = items[i].name + counter;
}
insertAfter(clone, newClone);
}
Here's a working copy on jsFiddle.
P.s. I wasn't sure if you wanted the new fields clearing so I left them.
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>
I am developing this for use in Internet Explorer 8 (because at work we have to use it). I have a page that has a table withing a form. The table has a button to "clone" rows, "AddScheduleRow()". That part works good. Each row has a button to delete that row "DeleteRow(r)". That part works well too. I also have a script to rename/renumber each row, "RenumberRows()". It almost works good. I can rename the text fields (for example what was previously StartDate3 now becomes StartDate2). However, in each row is an input that is type="image" and it is named like you should with any input. The name of it is "StartDateCal". The problem is that during the renaming process, when it hits the image input (TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;), I get a JavaScript error "'TheForm.StartDateCal' is null or not an object". I cannot figure this one out and it's standing in the way of moving on.
What can I do to try to rename an < input type = image /> ?
Below is the necessary code:
HTML
<html>
<head>
</head>
<body>
<form name="UpdateSchedule" method="post" action="DoSchedule.asp">
<input type="hidden" name="NumRows" value="0">
<input type="hidden" name="RowsAdded" value="0">
<table id="ClassScheduleTable">
<tr id="ScheduleRow" style="display:none;">
<td>
<input type="text" name="RowNum" value="0" size="1" onclick="alert(this.name)">
</td>
<td>
<b>Start Date</b> <input type="text" name="StartDate" value="" onclick="alert(this.name);" size="8">
<input type="image" name="StartDateCal" src="http://www.CumminsNorthwest.com/ATT/Img/Calendar3.png" style="border-style:none;" onClick="alert('name = ' + this.name);return false;">
</td>
<td>
<input type="button" value="Del." name="DelRow" class="subbuttonb" onclick="DeleteRow(this);">
</td>
</tr>
<tr>
<td colspan="3" style="text-align:right">
<input type="button" value="Add Class Date" class="SubButton" onclick="AddScheduleRow();">
</td>
</tr>
</table>
</form>
</body>
<script language="JavaScript">
JS
var TheForm = document.forms.UpdateSchedule;
var NumRows =0;
var RowsAdded =0;
function AddScheduleRow(){
NumRows++;
TheForm.NumRows.value = NumRows;
RowsAdded++;
TheForm.RowsAdded.value = RowsAdded;
var TableRowId = "ScheduleRow";
var RowToClone = document.getElementById(TableRowId);
var NewTableRow = RowToClone.cloneNode(true);
NewTableRow.id = TableRowId + NumRows ;
NewTableRow.style.display = "table-row";
var NewField = NewTableRow.children;
for (var i=0;i<NewField.length;i++){
var TheInputFields = NewField[i].children;
for (var x=0;x<TheInputFields.length;x++){
var InputName = TheInputFields[x].name;
if (InputName){
TheInputFields[x].name = InputName + NumRows;
//alert(TheInputFields[x].name);
}
var InputId = TheInputFields[x].id;
if (InputId){
TheInputFields[x].id = InputId + NumRows;
//alert(TheInputFields[x].id);
}
}
}
var insertHere = document.getElementById(TableRowId);
insertHere.parentNode.insertBefore(NewTableRow,insertHere);
RenumberRows();
}
AddScheduleRow();
function DeleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("ClassScheduleTable").deleteRow(i);
NumRows--;
TheForm.NumRows.value = NumRows;
RenumberRows();
}
function RenumberRows(){
var TempCounter = 0;
for (var i=0;i<=RowsAdded;i++){
if (TheForm.RowNum[i]){
TempCounter++;
TheForm.RowNum[i].name = "RowNum" + TempCounter;
TheForm.RowNum[i].value = TempCounter;
TheForm.StartDate[i].name = "StartDate" + TempCounter;
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
}
}
}
</script>
</html>
might be to do with your DTD,
try HTML4 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
You can use
document.getElementsByName('StartDateCal')[i].name = "StartDateCal" + TempCounter;
instead of
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
this is a sample code of what I am doing. unfortunately the alert(nextElem.value) returns "undefined" when I click the second checkbox to get the href of the link after it. do you have any idea how to fix it?
<HTML>
<HEAD>
<TITLE>Checkbox Inspector</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
for (i = 0; i <(document.f1.checkThis.length) ; i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem.href);
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="f1">
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate()">Check here<BR>
click here
</FORM>
</BODY>
</HTML>
Get the link's href with jQuery
http://jsfiddle.net/mplungjan/H9Raz/ :
$('form input:checkbox').click(function () {
alert($(this).nextAll('a').attr("href"));
});
Because of the BRs we need the nextAll, surprisingly since I was using the next selector with an "a"
See here why it did not work: Cleanest way to get the next sibling in jQuery
Get the link's href with forms access and usage of ID - no jQuery
http://jsfiddle.net/mplungjan/fKE3v/
window.onload=function() {
var chks = document.getElementsByName('checkThis');
for (var i=0;i<chks.length;i++) {
chks[i].onclick=function() {
var id = this.id;
var linkId="link_"+id.split("_")[1]
alert(document.getElementById(linkId).href)
}
}
}
<form>
<div>
<input type="checkbox" name="checkThis" id="chk_1" value="http://www.google.com" />Check here<br/>
click here<br>
<input type="checkbox" name="checkThis" id="chk_2" value="http://www.bing.com" />Check here<br/>
click here
</div>
</form>
Forms access to get the next checkbox
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate(this.form)">Check here<BR>
<INPUT TYPE="checkbox" NAME="checkThis" onClick="validate(this.form)">Check here2<BR>
function validate(theForm) {
var chk = theForm.checkThis
for (i = 0; i <chk.length) ; i++) {
if (chk[i].checked) {
var nextElem = chk[i+1];
if (nextElem) alert(nextElem.value);
}
}
}
Your problem is that nextElem is the text node immediately after your checkbox, not the next checkbox; text nodes don't have value attributes. For example, try this:
function validate() {
for (i = 0; i < (document.f1.checkThis.length); i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem);
alert(nextElem.value);
}
}
}
Or, for your convenience:
http://jsfiddle.net/ambiguous/sUzBL/1/