i want to do a very simple thing. I want to populate the list of a drop-down box based on the value of the 1st drop-down box. So these 2 boxes are the only elements in a table, which creates rows dynamically(on the click of a button). I am a newbie in html.. and have almost spent 2 entire days in vain in this...
This is the code:
HTML Code:
<table border="1" id="areas">
<tr>
<th colspan="3">Areas Serviced</th>
</tr>
<tr>
<td>
<select name='city1' id='city1' onChange="dynamic1(this,'txtRow1');">
<option value="">Please select a city</option>
<option value='Bangalore'> Bangalore </option>
<option value='Mumbai'> Mumbai</option>
</select>
<option></option>
</td>
<td>
<select name="txtRow1" id="txtRow1">
<option value="">Please Select an area</option>
<option></option>
</select>
</td>
</tr>
</table>
<input type="button" value="Add another Area" onClick="addRowToTable();" /> <input type="button" value="Remove" onClick="removeRowFromTable();" />
</br>
</br>
<input type="submit" name="submit" id="submit" value="Submit" />
Javascript:
function dynamic1(parent,child){
var parent_array = new Array();
parent_array[''] = ['Please select a city'];
parent_array['Bangalore'] = ['Marathahalli','Kadubeesanahalli'];
parent_array['Mumbai'] = ['Andheri','Santacruz'];
var thechild = document.getElementById(child);
thechild.options.length = 0;
var parent_value = parent.options[parent.selectedIndex].value;
if (!parent_array[parent_value]) parent_value = '';
thechild.options.length = parent_array[parent_value].length;
for(var i=0;i<parent_array[parent_value].length;i++){
thechild.options[i].text = parent_array[parent_value][i];
thechild.options[i].value = parent_array[parent_value][i];} }
function addRowToTable()
{
var tbl = document.getElementById('areas');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var col = document.createElement("TR");
var cell1 = document.createElement("TD");
var txt0= document.createTextNode(iteration);
var combo1=document.createElement("select");
var combo11=document.createElement("option");
var combo12=document.createElement("option");
var combo2=document.createElement("select");
var combo21=document.createElement("option");
var combo22=document.createElement("option");
var id2=combo2.id;
combo1.setAttribute("name","city");
combo1.setAttribute("onChange","dynamic1(this,id2);");
combo11.setAttribute("value","Bangalore");
combo11.innerHTML="Bangalore";
combo12.setAttribute("value","Mumbai");
combo12.innerHTML ="Mumbai";
combo2.setAttribute("name","area");
combo2.setAttribute("id","txtRow"+iteration);
combo1.appendChild(combo11);
combo1.appendChild(combo12);
combo2.appendChild(combo21);
combo2.appendChild(combo22);
var cell2 = document.createElement("TD");
cell2.appendChild(combo1);
var cell3 = document.createElement("TD");
cell3.appendChild(combo2);
col.appendChild(cell2);
col.appendChild(cell3);
tbl.appendChild(col);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
This code does not work.
Alternate Javascript code:
function SetMedia(objCity,iteration) {
var objArea = document.getElementById("txtRow"+iteration);
objArea.options.length = 0;
objArea.disabled = false;
switch (objCity.value) {
case "Bangalore":
objArea.options.add(new Option("Marathahalli"));
objArea.options.add(new Option("Kadubeesanahalli"));
break;
case "Mumbai":
objArea.options.add(new Option("Andheri"));
objArea.options.add(new Option("Santacruz"));
break;
default:
objArea.options.add(new Option("select"));
objArea.disabled = true;
break;
}
}
function addRowToTable()
{
var tbl = document.getElementById('areas');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var col = document.createElement("TR");
var cell1 = document.createElement("TD");
var txt0= document.createTextNode(iteration);
var combo1=document.createElement("select");
var combo11=document.createElement("option");
var combo12=document.createElement("option");
var combo2=document.createElement("select");
var combo21=document.createElement("option");
var combo22=document.createElement("option");
combo1.id="city"+iteration;
var id1=combo1.id;
combo2.id="txtRow"+iteration;
var id2=combo2.id;
combo1.setAttribute("name","city");
combo1.onChange=func(){SetMedia(id1,iteration);}
combo11.setAttribute("value","Bangalore");
combo11.innerHTML="Bangalore";
combo12.setAttribute("value","Mumbai");
combo12.innerHTML ="Mumbai";
combo2.setAttribute("name","area");
combo2.setAttribute("id","txtRow"+iteration);
combo1.appendChild(combo11);
combo1.appendChild(combo12);
combo2.appendChild(combo21);
combo2.appendChild(combo22);
var cell2 = document.createElement("TD");
cell2.appendChild(combo1);
var cell3 = document.createElement("TD");
cell3.appendChild(combo2);
col.appendChild(cell2);
col.appendChild(cell3);
tbl.appendChild(col);
}
Basically, I am not able to link the dynamically created object(drop-down number 2) to drop-down number 1 since I am not able to get the 'id's of the elements dynamically generated...
After this, I also need to use these values entered in another php script using POST...
This part doesn't work. You can't write to the .length property of an array or collection.
thechild.options.length = 0;
var parent_value = parent.options[parent.selectedIndex].value;
if (!parent_array[parent_value]) parent_value = '';
thechild.options.length = parent_array[parent_value].length;
for(var i=0;i<parent_array[parent_value].length;i++){
thechild.options[i].text = parent_array[parent_value][i];
thechild.options[i].value = parent_array[parent_value][i];} }
replace with
while (thechild.options[0]) thechild.removeChild(thechild.options[0]);
var parent_value = parent.options[parent.selectedIndex].value;
if (parent_array[parent_value]) {
for(var i=0;i<parent_array[parent_value].length;i++){
var o = document.createElement('option');
o.text = parent_array[parent_value][i];
o.value = parent_array[parent_value][i];} }
thechild.appendChild(o);
}
}
In the first javascript you are attempting to read the id attribute of combo2 before you have set it.
In the second javascript you are just adding two empty options to the select element (combo2).
Related
I need some help in displaying all the values in a Firebase database, in a table.
As is, it is just displaying the first value in the table alone
Results:
var tblCodes = document.getElementById('tbl_qrcode_list');
var databaseRef = firebase.database().ref('qrcode/');
var rowIndex = 1;
databaseRef.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblCodes.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
cellId.appendChild(document.createTextNode(childKey));
cellName.appendChild(document.createTextNode(childData.qrcode_desc));
rowIndex = rowIndex + 1;
});
});
function save_code(){
var qrcode_desc = document.getElementById('qrcode_desc').value;
var qrcode_grp = document.getElementById('qrcode_grp').value;
var qrcode_stg = document.getElementById('qrcode_stg').value;
var qrcode_img = document.getElementById('qrcode_img').value;
var qrid = firebase.database().ref().child('qrcode').push().key;
var data = {
qrcode_id: qrid,
qrcode_desc: qrcode_desc,
qrcode_grp: qrcode_grp,
qrcode_stg: qrcode_stg,
qrcode_img: qrcode_img,
}
You need to create a cell for each value here :
you need to create cells for each data
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cellName.appendChild(document.createTextNode(childData.qrcode_desc));
cellName.appendChild(document.createTextNode(childData.qrcode_grp));
cell3.appendChild(document.createTextNode(childData.qrcode_id));
cell4.appendChild(document.createTextNode(childData.qrcode_img));
cell5.appendChild(document.createTextNode(childData.qrcode_stg));
I'm wanting to dynamically generate a table like the following using MySQL, PHP, JS and HTML:
___________________________________________
[] | Please Select Service | Text Box |
-------------------------------------------
Add Row Delete Row
So the first column is a checkbox used for row deletion.
The second column is a Select box dynamically populated from a database
The third column by default is hidden, and shown when "Other" is selected and hidden when "Other" is not selected.
Therefore when "Add Row" is pressed it will look like the following:
___________________________________________
[] | Please Select Service | Text Box |
-------------------------------------------
___________________________________________
[] | Please Select Service | Text Box |
-------------------------------------------
Add Row Delete Row
My problem is I can only hide/show the very first text box unless the first text box is already shown when "Add Row" is pressed, if that occurs the new text box will show but can't be hidden, the "Add Row" and "Delete Row" buttons function as their names state. I'm guessing it has something to do with the value associated to the last option element in the select field.
Code Snippets can be seen below for the addRow, deleteRow and hide/show functions, as well as a the HTML that I'm using to display it.
JS
var boxCount = 1;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var theSelect = document.getElementById('services');
var lastValue = theSelect.options[theSelect.options.length - 1].value;
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
newcell.childNodes[0].id = "otherService" + boxCount;
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
newcell.childNodes[0].options[lastValue].value = boxCount;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function hideShowOtherBox(e) {
var theSelect = document.getElementById('services');
var lastValue = theSelect.options[theSelect.options.length - 1].value;
var ele = 'otherService' + lastValue;
if (e.options[e.selectedIndex].text == "Other") {
if (document.getElementById(ele).style.display == "none") {
document.getElementById(ele).style.display = "block";
}
} else {
document.getElementById(ele).style.display = "none";
}
}
HTML
<table id="dataTable" width="350px" border="1">
<tr>
<td><input type="checkbox" name="chk[]"/></td>
<td>
<select id='services' name="services[]" onChange='hideShowOtherBox(this);'>
<option value="Select">Please Select</option>
<?php
$servicesList = getAllServices();
foreach($servicesList as $x) {
echo "<option value='$x'>$x</option>\n";
}
?>
<option value='0'>Other</option>
</select>
</td>
<td><input id='otherService0' style='display:none;' type="text" name="otherService[]"/></td>
</tr>
</table>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
Try this:
var boxCount = 1;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
}
I am not very experienced just a learner.
Now come to the question.
I have a dynamic table codes are below: works fine as intended.
<head>
<style type="text/css">
<!--
#tblitemsgrid
td {
padding: 0.5em;
}
.classy0 { background-color: #234567; color: #89abcd; }
.classy1 { background-color: #89abcd; color: #234567; }
th {
padding: 0.5em;
background:#39C;
text-align:center;
}
-->
</style>
<script type="text/javascript">
var INPUT_NAME_PREFIX = 'input'; // this is being set via script
var RADIO_NAME = 'totallyrad'; // this is being set via script
var TABLE_NAME = 'tblitemsgrid'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var hasLoaded = false;
window.onload=fillInRows;
function fillInRows()
{
hasLoaded = true;
addRowToTable();
}
// CONFIG:
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five)
{
this.one = one; // text object
this.two = two; // text object
this.three = three; // text object
this.four = four; // text object
}
/*
* insertRowToTable
* Insert and reorder
*/
function insertRowToTable()
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var rowToInsertAt = tbl.tBodies[0].rows.length;
for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
}
addRowToTable(rowToInsertAt);
reorderRows(tbl, rowToInsertAt);
}
}
/*
* addRowToTable
function addRowToTable(num)
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// CONFIG: requires classes named classy0 and classy1
row.className = 'classy' + (iteration % 2);
// CONFIG: This whole section can be configured
// cell 0 - text - Serial Number
var cell0 = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cell0.appendChild(textNode);
// cell 1 - input text - Account name
var cell1 = row.insertCell(1);
var txtInpACC = document.createElement('input');
txtInpACC.setAttribute('type', 'text');
txtInpACC.setAttribute('name', 'accname' + iteration);
txtInpACC.setAttribute('size', '40');
txtInpACC.setAttribute('value', iteration);
cell1.appendChild(txtInpACC);
// cell 2 - input box- Dr amount
var cell2 = row.insertCell(2);
var txtInpDR = document.createElement('input');
txtInpDR.setAttribute('type', 'text');
txtInpDR.setAttribute('name', 'DrAmount' + iteration);
txtInpDR.setAttribute('size', '10');
txtInpDR.setAttribute('value', iteration); // iteration included for debug purposes
cell2.appendChild(txtInpDR);
// cell 3 - input box- Cr amount
var cell3 = row.insertCell(3);
var txtInpCR = document.createElement('input');
txtInpCR.setAttribute('type', 'text');
txtInpCR.setAttribute('name', 'CrAmount' + iteration);
txtInpCR.setAttribute('size', '10');
txtInpCR.setAttribute('value', iteration); // iteration included for debug purposes
cell3.appendChild(txtInpCR);
// cell 4 - input button - Delete
var cell4 = row.insertCell(4);
var btnEl = document.createElement('input');
btnEl.setAttribute('type', 'button');
btnEl.setAttribute('value', 'Delete');
btnEl.onclick = function () {deleteCurrentRow(this)};
cell4.appendChild(btnEl);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInpACC, txtInpDR, txtInpCR, btnEl);
}
}
// CONFIG: this entire function is affected by myRowObject settings
function deleteCurrentRow(obj)
{
if (hasLoaded) {
var oRows = document.getElementById('tblitemsgrid').getElementsByTagName('tr');
var iRowCount = (oRows.length - 2);
if (iRowCount <1+1) {
alert('Your table has ' + iRowCount + ' row(s). Row count can not be zero.');
return
}
var delRow = obj.parentNode.parentNode;
var tbl = delRow.parentNode.parentNode;
var rIndex = delRow.sectionRowIndex;
var rowArray = new Array(delRow);
deleteRows(rowArray);
reorderRows(tbl, rIndex);}
}
function reorderRows(tbl, startingIndex)
{
if (hasLoaded) {
if (tbl.tBodies[0].rows[startingIndex]) {
var count = startingIndex + ROW_BASE;
for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count; // input text
var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' ');
tbl.tBodies[0].rows[i].myRow.two.value = count + ' was' + tempVal[0];
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.four.value = count; // input radio
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}
}
}
}
function deleteRows(rowObjArray)
{
if (hasLoaded) {
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRow2NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRow2NewWindow';
// submit
frm.submit();
}
</script>
</head>
<body>
<form action="tableaddrow_nw.php" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Insert [I]" onclick="insertRowToTable();" />
<!--<input type="button" value="Delete [D]" onclick="deleteChecked();" />-->
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
</p>
<table border="0" cellspacing="0" id="tblitemsgrid" width=600>
<thead>
<tr>
<th colspan="5">Sample table</th>
</tr>
<tr>
<th>E.#</th>
<th>Account name</th>
<th>Debit</th>
<th>Credit</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</body>
</html>
This is a processing page:
<head>
<title>Table Add Row - new window</title>
<script language="JavaScript">
<!--
function printToPage()
{
var pos;
var searchStr = window.location.search;
var searchArray = searchStr.substring(1,searchStr.length).split('&');
var htmlOutput = '';
for (var i=0; i<searchArray.length; i++) {
htmlOutput += searchArray[i] + '<br />';
}
return(htmlOutput);
}
//-->
</script>
</head>
<body>
<b>MREDKJ's Table Add Row</b>
<br />
Below should be the name/value pairs that were submitted:
<p>
<script language="JavaScript">
<!--
document.write(printToPage());
//-->
</script>
</p>
</body>
</html>
the above displays a result:
accname1=1
DrAmount1=1
CrAmount1=1
input2=2+was2
DrAmount2=2
CrAmount2=2
input3=3+was3
DrAmount3=3
CrAmount3=3
input4=4+was4
DrAmount4=4
CrAmount4=4
how can I pass javascript variables into PHP (which is server side and client side) in the above case ?
thanks alot in advance.
The way to pass variables from client-side to server-side is via HTTP Request. So either you redirect to a PHP page passing in the variable as GET query strings or POST data or you can also do an AJAX call of either GET or POST.
You can use jQuery and ajax to pass these informations to server easy way
And remember. PHP isn't client side language
$.ajax({
'url': 'ajax.php',
'type': 'POST',
'data': 'accname1='+accname1+'&input1='+input1+'&input2='+input2+'&input3='+input3+'&DrAmount1='+DrAmount1+'&DrAmount2='+DrAmount2+'&DrAmount3='+DrAmount3+'&CrAmount1='+CrAmount1'&CrAmount2='+CrAmount2'&CrAmount3='+CrAmount3,
'success': function(){
alert('data sent');
}
});
I am trying to make a form in which there will be a button, when clicking on it a Javascript function will be called and a new row with a textbox will be added. In simple words, when clicking on the button, new text will be added. Here is the function:
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);
}
Now please guide me: how can I set the default value of the text box and drop down box? I mean in this code where should I put <?php echo $data['pno'];?>
I have tried putting in the HTML form; for the first row it works but for the second row it doesn't work. Thanks.
i have solved in this way
<input type="button" value="Add" onClick="addRowToTable(<?php echo $data['pno'];?>);" />
and on the javascript side
function addRowToTable(a)
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.value=a; // here i have achived the value
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
}
might be its not a good solution but for my case it works
How about you save the default value in a separate JS variable in your html like:
var defaultValue = "<?php echo $data['pno'];?>";
Or try this:
var defaultValue = "<?= $data['pno'] ?>";
Then when you are adding new input you can use it like this:
el.value = defaultValue;
The invoice input values which hold the totals of invoice line items that get updated via JS return a NULL value when they are submitted.
<span class="sublabel">Subtotal</span><input type="text" class="total-box" id="product-subtotal" readonly="true" />
<span class="sublabel">Tax</span><input type="text" class="total-box" id="product-tax" readonly="true" />
<span class="sublabel">Total</span><input type="text" class="total-box" id="order-total" readonly="true" />
The JS
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
function calcTaxTotal() {
var taxTotal = 0;
//var taxAmount = 10;
var taxAmount = $("#salesTaxAmount").val() || 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var taxTotal = parseInt(productSubtotal) * parseInt(taxAmount) / 100;
var taxTotalNice = taxTotal;
$("#product-tax").val(taxTotalNice);
};
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
$(function(){
$('.row-total-input').each(
function( intIndex ){
$('.invAmount').livequery('blur', function() {
var $this = $(this);
var amount = $this.val();
var qty = $this.parent().find('.invQty').val();
if ( (IsNumeric(amount)) && (amount != '') ) {
var rowTotal = qty * amount;
$this.css("background-color", "white").parent().find(".row-total-input").val(rowTotal);
} else {
$this.css("background-color", "#ffdcdc");
};
calcProdSubTotal();
calcTaxTotal()
calcOrderTotal();
});
}
);
});
I originally had the inputs set as disabled however I have changed them to readonly because disabled fields can't be submitted.
What am i missing?
Thanks in advance.
You haven't set a name-attribute on your <input />s, so PHP can't access their values, and returns nothing when you look for $_POST['product-tax']. If you have set error_reporting to E_ALL, you should see a notice telling you you are trying to access an undefined index on the $_POST array.