JavaScript/Jquery - Retrieving data in a row - javascript

I'm pretty new to JavaScript, so suppose I have the following function that I use to append a new row into a table. Could someone please give some suggestions how I would be able to get the value of the textarea boxes or check whether each checkbox is checked on the last row that I add to the table? I'm trying to use getElementByName() but a bit unsure on how to get the data on the specific row I want. The table is part of a jsp page. Thanks lots!!!
function generateNewRow(id){
var tr = "<tr>";
tr += "<td><input name='id' type='hidden' value='" + id + "' />";
tr += "<textarea name='a' style='width: 98%; height:40px'></textarea></td>";
tr += "<td>";
tr += "<input type='checkbox' name='b' value='" + id + "'/>B";
tr += "<input type='checkbox' name='c' value='" + id + "'/>C";
tr += "<input type='checkbox' name='d' value='" + id + "'/>D";
tr += "<input type='checkbox' name='e' value='" + id + "'/>E<br/>";
tr += "<input type='checkbox' name='f' value='" + id + "'/>F;
tr += "</td>";
tr += "<td><textarea name='g' style='width: 98%; height:40px'></textarea></td>";
tr += "</tr>";
$("#ProblemsGrid tbody").append(tr);
}

If you want to get the last row of the table you can use a selector like so:
$("#ProblemnsGris tbody tr:last");
For textarea and input values I would use find along with each:
$("#ProblemsGrid tr:last").find('input:checkbox').each(function(index, element){
var value = $(element).is(':checked');
alert(value);
});
$("#ProblemsGrid tr:last").find('textarea').each(function(index, element){
var value = $(element).val();
alert(value);
});
http://jsfiddle.net/Dqryf/

Related

Undefined offset in checkbox dynamic field

I have a dynamic field where user can add as many rows as it wants. There are 3 checkboxs in each row. after user added as much as they wanted they click a button and get sent to FgProcess.php.
FgTable.php
<script>
var FgRow = 0;
function addfg()
{
FgRow++;
var html = "<tr>";
html += "<td><input type='text' name='SKUDescription[]' class ='form-control'/></td>";
html += "<td><input type='text' name='LotNumber[]' class ='form-control'/></td>";
html += "<td><input type='text' name='BBD[]' class ='form-control'/></td>";
html += "<td><input type='text' name='Size[]' class ='form-control'/></td>";
html += "<td><input type='text' name='SizeUOM[]' class ='form-control'/></td>";
html += "<td><input type='text' name='UnitsPerCase[]' class ='form-control'/></td>";
html += "<td><input type='text' name='CaseCount[]' class ='form-control'/></td>";
html += "<td><input type='text' name='CasePartial[]' class ='form-control'/></td>";
html += "<td><input type='text' name='UnitsDamaged[]' class ='form-control'/></td>";
html += "<td><input type='text' name='UnitsLeak[]' class ='form-control'/></td>";
html += "<td><input type='text' name='UnitsSample[]' class ='form-control'/></td>";
html += "<td><input type='text' name='UnitTotal[]' class ='form-control'/></td>";
html += "<td><input type='text' name='NetWeightTotal[]' class ='form-control'/></td>";
html += "<td><input type='text' name='ProductTemperature[]' class ='form-control'/></td>";
html += "<td><input type='checkbox' name='Organic[]' value='1' class='custom-checkbox'/></td>";
html += "<td><input type='checkbox' name='OnHold[]' value='1' class='custom-checkbox'/></td>";
html += "<td><input type='checkbox' name='WIP[]' value='1' class='custom-checkbox'/></td>";
html += "<td style='width: 2%'></td>";
html += "</tr>";
document.getElementById("finishedgoods_row").insertRow().innerHTML = html;
}
My Problem is that I get an offset error when user does not check the checkboxes. I know the reason is that if not checked the value is NULL.
I tried fixing this issue by adding hidden input for each of my checkboxes but then I got extra checkbox values sometimes!
FgProcess.php
if (isset($_POST['fgAdd']))
{
$WOID = $_POST['id'];
print_r($_POST);
for ($i = 0; $i < count($_POST["SKUDescription"]); $i++)
{
$SKUDescription = $_POST["SKUDescription"][$i];
$LotNumber = $_POST["LotNumber"][$i];
$BBD = $_POST["BBD"][$i];
$Size = $_POST["Size"][$i];
$SizeUOM = $_POST["SizeUOM"][$i];
$UnitsPerCase = $_POST["UnitsPerCase"][$i];
$CaseCount = $_POST["CaseCount"][$i];
$CasePartial = $_POST["CasePartial"][$i];
$UnitsDamaged = $_POST["UnitsDamaged"][$i];
$UnitsLeak = $_POST["UnitsLeak"][$i];
$UnitsSample = $_POST["UnitsSample"][$i];
$UnitTotal = $_POST["UnitTotal"][$i];
$NetWeightTotal = $_POST["NetWeightTotal"][$i];
$ProductTemperature = $_POST["ProductTemperature"][$i];
if ($_POST["Organic"][$i]==null){$Organic = '0';}else{$Organic = $_POST["Organic"][$i];}
if ($_POST["OnHold"][$i]==null){$OnHold = '0';}else{$OnHold = $_POST["OnHold"][$i];}
if ($_POST["WIP"][$i]==null){$WIP = '0';}else{$WIP = $_POST["WIP"][$i];}
//after this part insert into mysql and check errors and etc
}
//the rest of if statement
I tried checking for NULL but it didn't work. Each of these lines gave me a Undefined offset: 1 error.
if ($_POST["Organic"][$i]==null){$Organic = '0';}else{$Organic = $_POST["Organic"][$i];}
if ($_POST["OnHold"][$i]==null){$OnHold = '0';}else{$OnHold = $_POST["OnHold"][$i];}
if ($_POST["WIP"][$i]==null){$WIP = '0';}else{$WIP = $_POST["WIP"][$i];}
for example when i tried to add two rows, with the first row checkboxes being checked and then second row not being checked, this is what i get when print_r($_POST)
[Organic] => Array ( [0] => 1 ) [OnHold] => Array ( [0] => 1 ) [WIP] => Array ( [0] => 1 )
I know the problem is from checkboxes since i had no problem when the 3 checkboxes were text.
I would appreciate any help.
The issue is that (for each category) all your checkbox inputs have the same name, so only one of them is being sent to the server. To pass an array of checkbox values to the server, you should include the row index inside the brackets in Organic[] and the others.
So, when adding rows, keep track of the row's index, and reflect the in the names of the checkbox inputs. Slightly modified your code to reflect what I mean:
var FgRow = 0;
function addfg()
{
FgRow++;
var html = "<tr>";
html += "<td><input type='checkbox' name=`Organic[${FgRow}]` value='1' class='custom-checkbox'/></td>";
html += "<td><input type='checkbox' name=`OnHold[${FgRow}]` value='1' class='custom-checkbox'/></td>";
html += "<td><input type='checkbox' name=`WIP[${FgRow}]` value='1' class='custom-checkbox'/></td>";
html += "<td style='width: 2%'></td>";
html += "</tr>";
document.getElementById("finishedgoods_row").insertRow().innerHTML = html;
}

How to display checkbox value (checked or unchecked )

I am working on a project and the project was created with ASP.Net mvc 5.
I get the data from the database and I just want to display the data on the user interface. My problem is, I have all the data I want in the browser console, but the checkboxes are not shown checked. How can I do this?
"<input type='checkbox' value='" +item.IsActive+"'/>"
Here is my code:
function success(data) {
var rows;
if (data != null) {
$.each(data, function (i, item) {
rows += "<tr>"
+ "<td>" +
"<label class='checkbox-container' id ='checkbox-container'>" +
item.Name+
"<input type='checkbox' value='" + item.IsActive+"'/>" +
"<span class='checkmark'>"+"</span>"+
"</label >"+
"</td>"
});
$('#myTable tbody').append(rows);
}
else {
alert("Something went wrong");
}
}
Maybe some js logic would help?
$.each(data, function (i, item) {
var checkbox_input = "<input type='checkbox' value='" + item.IsActive+"'/>";
if(item.IsActive){
var checkbox_input = "<input type='checkbox' value='" + item.IsActive+"' checked />";
}
rows += "<tr>"
+ "<td>" +
"<label class='checkbox-container' id ='checkbox-container'>" +
item.Name+
checkbox_input +
"<span class='checkmark'>"+"</span>"+
"</label >"+
"</td>"
});
Or Shorthand with template literal js
$.each(data, function (i, item) {
rows += "<tr>"
+ "<td>" +
"<label class='checkbox-container' id ='checkbox-container'>" +
item.Name+
`<input type='checkbox' value='${item.IsActive}' ${item.IsActive ? 'checked' : ''} />` +
"<span class='checkmark'>"+"</span>"+
"</label >"+
"</td>"
});
If you want a checkbox to show checked, it should have the checked attribute. In this case it would be something like:
<input type='checkbox' checked/>
Since you have a variable that tells you wether the checkbox is checked or not, you could try using:
"<input type='checkbox'" + item.isActive ? "checked" : "" + "/>"
This will render the checkbox as checked when item.isActive is true.

How to get the Dynamic Table cell value on button click

I've a table which is dynamically generated. In its row, I'm placing buttons.
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test()'></td>";
tr = tr + "</tr>";
};
On a button click, I'd like to get the particular cell value of that row. E.g.: If I click on the age in the first row, then the value I have to get is 50. And if I click on the button in second row, then I should get 94.
How can I get the table cell value on a button click?
Here is your solution for dynamic table:
<script language="javascript">
var tbl = document.getElementById("tblId");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
So, By using this javascript you can get value of any table cell.
You can pass age to button onclick function like onclick='test('"+resp[i].age +"')'
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test("+resp[i].age +")'></td>";
tr = tr + "</tr>";
};
Here is your solution:
$(document).find('.theButton').on('click',function(){
var age = $(this).parents('tr:first').find('td:eq(1)').text();
console.log(age);
});
Try this example with jQuery, I have replaced your function test, with rowid
https://jsfiddle.net/ucostea/2thyj0ft/
$(document).on("click", ".theButton", function(){
alert("Aage: "+$('.age_'+$(this).attr('rownr')+'').text());
});
for (var i = 0; i < 10; i++) {
var tr = "";
tr = tr + "<tr >";
tr = tr + "<td class='date_"+i+"'>Date" + i + "</td>";
tr = tr + "<td class='age_"+i+"'>Age " + i + "</td>";
tr = tr + "<td class='hour_"+i+"'>Hour " + i + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' rownr='" + i + "'></td>";
tr = tr + "</tr>";
$('.table tbody').append(tr);
};

Dynamically creating a form

On my page, I show a table of entries. At the end of the table is a "modify" button. When the button is clicked the row turns into a form for directly modifying the contents.
This code:
element.innerHTML = "<tr class='alt_col'>";
element.innerHTML += "<form action='/RIDT/includes/modify_codeplug.inc.php' method='POST' name='modify_form'>";
element.innerHTML += "<td><input type='text' name='fileName' value='" + fileName + "'></td>";
element.innerHTML += "<td><input type='text' name='location' value='" + loc + "'></td>";
element.innerHTML += "<td><input type='text' name='build' value='" + build + "'></td>";
element.innerHTML += "<td><input type='text' name='version' value='" + version + "'></td>";
element.innerHTML += "<td><select name='type' id ='selectType'>" + descOptions + "</select></td>";
element.innerHTML += "<td><input type='hidden' name='id' value='" + id + "'/><input type='submit' value='Submit'/></td>";
element.innerHTML += "</form>";
element.innerHTML += "</tr>";
var options = document.getElementById("selectType").options;
for (i = 0; i < options.length; i++)
{
if (options[i].text == desc)
{
options[i].selected=true;
}
}
Results in the form being created like this:
<form action="/RIDT/includes/modify_codeplug.inc.php" method="POST" name="modify_form"></form>
With all of the forms input elements coming after the closing element. Why is the form being closed early?
Thanks for the help everyone. I will research all the suggestions provided more deeply later. In the interest of saving time I did it a different way. Instead of submitting a form, the submit button calls another javascript function that picks out the input data from the DOM, then builds and submits a hidden form to my php script. It's not pretty, but it got the job done.
I didn't test this, but jQuery has the same problem if you try to insert an unclosed element into the DOM. The closing tag is added for you.
Try this instead:
//track the html as a single string var
var html = "<tr class='alt_col'>";
html += "<form action='/RIDT/includes/modify_codeplug.inc.php' method='POST' name='modify_form'>";
html += "<td><input type='text' name='fileName' value='" + fileName + "'></td>";
html += "<td><input type='text' name='location' value='" + loc + "'></td>";
html += "<td><input type='text' name='build' value='" + build + "'></td>";
html += "<td><input type='text' name='version' value='" + version + "'></td>";
html += "<td><select name='type' id ='selectType'>" + descOptions + "</select></td>";
html += "<td><input type='hidden' name='id' value='" + id + "'/><input type='submit' value='Submit'/></td>";
html += "</form>";
html += "</tr>";
// set the html string once
element.innerHTML = html;

Dynamic id does not work after removing row from table

I have a table with feeSetting id.It contain dynamic data , I can add and remove remove rows to table. I generated ids dynamically that work fine until user remove a rows and add again new row it override the unique id of last row. I want table to generate unique id with dynamic add and remove functionality . My code for adding row is as follow.
<tablen id="feeSetting ">
<tbody>
</tbody>
</table>
<script>
function AddRow() {
debugger;
var index = 0;
if ($("#feeSetting tbody tr").length > 0) {
index = $("#feeSetting tbody tr").length;
}
$("#feeSetting tbody").append("<tr class='gradeX'>"
+ "<td class='col-md-3'><input type='text' value='' class='form-control validate[required,custom[number]] text-input txtFromDay' id='eFromDay'/></td>"
+ "<td class='col-md-3'><input type='text' class='form-control validate[required,custom[number],min[1]] text-input txtValue' value='' id='eValue-" + index + "'/></td>"
+ "<td class='col-md-4'>"
+ "<div id='loadTypes-" + index + "' class='typeValidation'></div></td>"
+ "<td class='col-md-2'><input type='button' class='btn btn-danger btn-sm' value=' Remove '/></td>"
+ "</tr>");
renderPartialInDiv('#Url.Action("GetValidationTypeDropDown", "FeeFineSetting")?strDDName=eValidationTypeList-' + index + '&intDDID=0&intValidationID=1', '#loadTypes-' + index);
$('#eValidationTypeList-'+index).select2();
};
</script>
Try using one global variable which will increment its value on addition of each new row, see below code
<tablen id="feeSetting ">
<tbody>
</tbody>
</table>
<script>
//keep this variable outside function and use it as global variable.
var index = 0;
function AddRow() {
debugger;
index++;
$("#feeSetting tbody").append("<tr class='gradeX'>"
+ "<td class='col-md-3'><input type='text' value='' class='form-control validate[required,custom[number]] text-input txtFromDay' id='eFromDay'/></td>"
+ "<td class='col-md-3'><input type='text' class='form-control validate[required,custom[number],min[1]] text-input txtValue' value='' id='eValue-" + index + "'/></td>"
+ "<td class='col-md-4'>"
+ "<div id='loadTypes-" + index + "' class='typeValidation'></div></td>"
+ "<td class='col-md-2'><input type='button' class='btn btn-danger btn-sm' value=' Remove '/></td>"
+ "</tr>");
renderPartialInDiv('#Url.Action("GetValidationTypeDropDown", "FeeFineSetting")?strDDName=eValidationTypeList-' + index + '&intDDID=0&intValidationID=1', '#loadTypes-' + index);
$('#eValidationTypeList-'+index).select2();
};
</script>

Categories