I have a basic task list with due dates. The CSS script for showing overdue dates works. If I add new entries via the from input the css is not applied to overdue items. I have researched event delegation on here and adjusted code to include .on for delegation. Spent a long while trying to solve this but any help would be appreciated.
<head>
<script type="text/javascript">
$(document).ready(function() {
$(".add-row").on('click', function() {
var task = $("#task").val();
var date = $("#date").val();
var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
$('table tbody').append(markup);
});
});
</script>
<script>
$(function() {
$('table td').each(function() {
var row_date =
Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/,
'$2/$1/$3'));
var now_date = new Date().getTime();
if (row_date < now_date) {
$(this).parent('tr').addClass('past');
}
});
});
</script>
</head>
<body>
<form>
<input type="text" id="task" placeholder="task" />
<input type="text" id="date" placeholder="dd/mm/yyyy" />
<input type="button" class="add-row" value="Add Row" />
</form>
<table id="task_table">
<thead>
<tr>
<th>Task</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mow lawn</td>
<td>01/02/2017</td>
</tr>
<tr>
<td>Clean car</td>
<td>01/02/2017</td>
</tr>
<tr>
<td>Empty bins</td>
<td>01/02/2018</td>
</tr>
</tbody>
</table>
<style>
#task_table tr.past {
background: #ff8a33;
}
</style>
</body>
</html>
I did a jsfiddle that gets you partially there. There's still an issue when you load, but that should get you going:
$(document).ready(function(){
$(".add-row").on('click',function(){
var task = $("#task").val();
var date = $("#date").val();
var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
$('table tbody').append(markup);
checkDate();
});
function checkDate() {
$('table td').each(function() {
var row_date = Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3'));
var now_date = new Date().getTime();
if(row_date < now_date) {
$(this).closest('tr').addClass('past');
}
});
}
});
jsfiddle
Try to apply the CSS to the cells in that row, not to the row itself:
#task_table tr.past td {
background: #FF8A33;
}
Related
I have a web page for applying. In this web page, rows are dynamic add after addp button clicked.I can add new row successfully with addPf() method. And these input name attribute should be enName0, enName1, enName2....., but it works fail with name="enName"+aDWI.
Here is my html code:
<div>
<table>
<tr>
<td>
<input type="button" id="addP" onclick="addPf()" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Here is my javascript code:
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>
name="enName"+aDWI is not right.I have no idea about this, who can help me ?
Change from
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
to
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
The issue is because you need to concatenate the variable in the string correctly, using the ' character.
Also note that you should really be using unobtrusive event handlers instead of the outdated on* event attributes. In addition, you can simplify the logic by using jQuery's append(), like this:
var aDWI = 0;
$('#addP').click(function() {
newrow = '<tr><td><input style="width:98%" name="enName' + aDWI + '" value="' + aDWI + '"></td></tr>';
$('#staTable').append(newrow);
aDWI = aDWI + 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table id="staTable">
<tr>
<td>
<input type="button" id="addP" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Just update it with
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>
I have gone through google and some of SO questions (such as this & this) as well but I didn't find the solution.
I am working for validation of a dynamically generated rows in a table,initially I am trying to validate the first td, loop and alert is working all fine but document.getElementById() is giving a null value. The script is at the very bottom of the page.
and here is the JS code.
edit: I have added the code, and what I am trying to do is display the error (Please fill) when field is left blank on the click of submit button and hide it when it is filled.
$(function(){
$(document).on("click",".addRowAux",function(){
/*var valanx1 = $(this).parents("tr").children("td:nth-child(2)").children("input").val();
var valanx2 = $(this).parents("tr").children("td:nth-child(3)").children("input").val();
var valanx3 = $(this).parents("tr").children("td:nth-child(4)").children("select").val();
var valanx4 = $(this).parents("tr").children("td:nth-child(4)").children("input").val();*/
var countrow= $("#annextable tr").length;
/*countrow++;*/
if(countrow<11)
{
$("#aux").append('<tr><td align="center">'+countrow+'</td><td align="center"><input type="text" name="ref_name[]" id="ref_name"/><span id="refNm_error">Please fill</span></td><td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td><td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td><td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td><td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td><td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td><td align="center"><span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td></tr>');
}
else
{
//countrow--;
alert("Can not add more then 10 record.");
}
});
});
$(document).on('click', '#removeRowaux', function () { // <-- changes
var countrow= $("#annextable tr").length;
if(countrow>3)
{
$(this).closest('tr').remove();
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{
tblObj.rows[i+1].cells[0].innerHTML = i+1;
tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1);
////alert(kj);
//document.getElementById("refNm_error").id ="refNm_error"+j;
}
}
else{
alert("you can not delete this")
}
});
$(document).on('click', '#hods', function () {
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1)
var j=tblObj.rows[i+1].cells[1].getAttribute("delThis");
document.getElementById("refNm_error").id ="refNm_error"+j;
}
});
$(function(){
$(document).on('change', '.rel_type', function() {
var relation = $(this).val();
if(relation =='OT'){
$(this).next("input").show();
$(this).next("input").val("Please Specify");
}
else{
$(this).next("input").hide();
$(this).next("input").val("")
}
});
});
function yoVal(){
var refNm =document.getElementsByName('ref_name[]');
for(var i=0;i<=refNm.length;i++) {
if(refNm[i].value==""){
alert("success");
}
else{
var ch ='refNm_error'+(i+1);
alert(ch);
//document.getElementById(ch).style.display = "none";
alert("fail")
}
}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="refForm">
<table width="99%" border="1" id="annextable" style="border-collapse:collapse" align="center">
<thead>
<tr style="background:#ddd;">
<th>S.No</th>
<th>Name</th>
<th>Designation</th>
<th>Address</th>
<th>Email</th>
<th>Mobile</th>
<th>PAN</th>
<th>Action</th>
</tr>
</thead>
<tbody id="aux">
<tr>
<td align="center">1</td>
<td align="center"><input type="text" name="ref_name[]" id="ref_name"/><br/><span id="refNm_error">Please fill</span></td>
<td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td>
<td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td>
<td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td>
<td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td>
<td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td>
<td align="center">
<span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td>
</tr>
</tbody></table>
<input type="button" onclick="yoVal()" value="Test" id="hods"/>
</div>
Because you are adding extra quotes in beginning and end in variable k. use:
var k = 'refNm_error' + (i+1);
You might need to reload the DOM after adding dynamic elements.
This link might help
Update, when you created your dynamic table rows for the table you didn't assign unique ids for input elements. So I updated the addRow handler:
$(document).on("click", ".addRowAux", function () {
to add unique input ids, like following:
$("#aux").append('<tr><td align="center">' + countrow + '</td><td align="center"><input type="text" name="ref_name[]" id="ref_name_' + countrow + '"/><span id="refNm_error_' + countrow + '">Please fill</span>...
and also I changed in the code:
<span id="removeRowaux">Remove</span>
to use class instead of an id:
<span class="removeRowaux">Remove</span>
Now the remove row handler listens to events from spans with class removeRowaux:
$(document).on('click', '.removeRowaux', function ()
Now the remove row functionality works and there are no spans with identical ids. So I don't think there was anything wrong with getElementById() in the code - it works fine :-)
Updated Fiddle
I am using the below script in my python application for generating rows of form fields by clicking an “add row” button. But I am able to do this only if there is at-least one blank row, can I get some help in getting the below script changed so that new row can be added without any blank rows. Also I need to have a timepicker field in the same row
$(function() {
$("div[data-toggle=fieldset]").each(function() {
var $this = $(this);
//alert($this)
//Add new entry
$this.find("button[data-toggle=fieldset-add-row]").click(function() {
var target = $($(this).data("target"))
console.log(target);
var oldrow = target.find("tr[data-toggle=fieldset-entry]:last");
var row = oldrow.clone(true, true);
console.log(row.find(":input")[0]);
var elem_id = row.find(":input")[0].id;
var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
row.attr('data-id', elem_num);
row.find(":input").each(function() {
console.log(this);
var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
$(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
});
oldrow.after(row);
}); //End add new entry
//Remove row
$this.find("button[data-toggle=fieldset-remove-row]").click(function() {
if($this.find("tr[data-toggle=fieldset-entry]").length > -1) {
var thisRow = $(this).closest("tr[data-toggle=fieldset-entry]");
thisRow.remove();
}
});
//End remove row
});
});
HTML used as below
<div class="form-group">
<div data-toggle="fieldset" id="dimdetail-fieldset">
<div class="col-sm-5">
<button type="button" class="btn btn-primary pull-left" data-toggle="fieldset-add-row" data-target="#dimdetail-fieldset" id="add_time"> + Time</button>
</div>
<br>
<br>
<br>
<div class="col-md-12">
<div class ="table-responsive">
<table id="table_id" class="table table-bordered">
<tr>
<th>Total Hours</th>
<th>Inspector</th>
<th>Inspection</th>
<th>Remarks</th>
<th></th>
</tr>
<tr data-toggle="fieldset-entry">
<td><input class="form-control" id="timesheet_time_details-0-total_hours" name="timesheet_time_details-0-total_hours" size="12" type="text" value="">
</td>
<td><input class="form-control" id="timesheet_time_details-0-inspector" name="timesheet_time_details-0-inspector" size="12" type="text" value="">
</td>
<td><select class="form-control" id="timesheet_time_details-0-testmethod" name="timesheet_time_details-0-testmethod"><option value="1">Test Method</option><option value="2">UT Test</option></select>
</td>
<td><textarea class="form-control" id="timesheet_time_details-0-remarks" name="timesheet_time_details-0-remarks" rows="3"></textarea>
</td>
<td><button type="button" data-toggle="fieldset-remove-row" id="dimdetail-0-remove">-</button></td>
</tr>
</table>
</div>
</div>
</div>
</div>
thanks ,
prasobhraj
$(function() {
// $("div[data-toggle=fieldset]").each(function() {
var $this = $(this);
//alert($this)
//Add new entry
$this.find("button[data-toggle=fieldset-add-row]").click(function() {
var target = $($(this).data("target"))
console.log(target);
var oldrow = target.find("tr[data-toggle=fieldset-entry]:last");
var row = oldrow.clone(true, true);
console.log(row.find(":input")[0]);
var elem_id = row.find(":input")[0].id;
var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
row.attr('data-id', elem_num);
row.find(":input").each(function() {
console.log(this);
var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
$(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
});
oldrow.after(row);
}); //End add new entry
//Remove row
$this.find("button[data-toggle=fieldset-remove-row]").on('click',function() {
if($this.find("tr[data-toggle=fieldset-entry]").length > -1) {
var thisRow = $(this).closest("tr[data-toggle=fieldset-entry]");
thisRow.remove();
}
});
});
try this its working..
Below is a form when submitted displays the content in a table.
What works
Content is successfully transferred via form to table.
What is not working
I wanted to hide the table when the page loads and be displayed only after the form is submitted.
I tried #myTableData {visibility: hidden;} in css and then I tried plugging (.style.visibility="visible";) Javascript in my addtable function to display the table but it does not work. I am not sure if I am understanding this right.
Also how do I control the display of the table (like width, background color, font etc). I added (td.style.width = '200px'; but I don't see any changes).
CSS or JS for controlling table ?
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
1) In function addRow add table.style.visibility = "visible"; ,to display the table, right after var table = document.getElementById("myTableData");.
2) To set styles like width you can can use setAttribute method.
document.getElementById('myTableData').setAttribute("style","width:200px");
Note: I can't see where you make use of addTable function, maybe this is why some of styles are not setted when you want.
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
table.style.visibility = "visible";
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
I don't have the rep to comment so I can't ask for details, but just in case you can use jquery, you can hide and show stuff like this:
$(function(){
$("#add").click(function() {
var name = $('#name').val();
var domain = $('#domain').val();
var url = $('#url').val();
$('#hidey').show();
$('#nametd').html(name);
$('#domtd').html(domain);
$('#urltd').html(url);
})
});
https://jsfiddle.net/6dxLsnL4/
Or trigger on form submit instead of click if you want, but there, you might want to consider ajax, because then you can make sure the form is processed on the server side before displaying the results.
This is the html markup
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js">
</script>
<style type="text/css">
div{ padding:4px; }
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(
function() {
var counter = 2;
$('a.add').live('click', function() {
if (counter > 5) {
alert("Only 5 textboxes allowed");
return false;
}
var newRow =
$(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
var i = 0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
$(this).text('Remove').removeClass('add').addClass('remove');
counter++;
});
$('a.remove').live('click', function() {
$(this).closest('tr').remove();
counter--;
var i=0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
});
$("#getButtonValue").click(function() {
var test='';
for(var i=0;i<5;i++){
var minValue = $('#Col'+(i++)).val().trim();
var maxValue = $('#Col'+i).val().trim();
if((minValue=='' && maxValue !='')||(minValue!='' && maxValue !='' && minValue > maxValue)){
alert('Alerting...');
}
}
var gridInAnswerValuesHtml = "";
$(".grdAns").each(function() {
//ansString += this.value+",";
gridInAnswerValuesHtml += "<input type = \"hidden\" name = \"gridInAnswers\" value = \"";
gridInAnswerValuesHtml += this.value;
gridInAnswerValuesHtml += "\">";
});
alert(gridInAnswerValuesHtml);
});
});
</script>
</head>
<body>
<div id="blankDiv"></div>
<table id="gridInAnswers">
<tr>
<th>
Min Value
</th>
<th>
Max Value
</th>
</tr>
<tr>
<td>
<input type="text" name="col1" id="Col0" class="grdAns" />
</td>
<td>
<input type="text" name="col1" id="Col1" class="grdAns" />
</td>
<td>
Add
</td>
</tr>
<tr>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</tr>
</table>
</body>
on click of the add button I want to remove the textbox but its contents should get displayed say inside a div. i.e. I want to stop user from modifying this but disabling the textbox is not an option. How do I achieve this ?
Basically what you need to do is to do the replacement as soon as you click on the add link. The replacement is really simple.
// Do the magic here (Kuroir)
$(this).parent().parent().find('input').each(function(){
$(this).replaceWith('<div class="inactive">' + $(this).val() + '</div>');
});
Basically, you're going back to the tr level, then finding the input and doing the replacement for that row.
Working Solution: http://jsfiddle.net/kuroir/SXppg/
To get content from an <input> and place it in a <div>, you want something like:
$('#target-div-id').text(
$('#Col0').val()
);
I'm reasonably sure that's what you're trying to do.