Validation on dynamically added rows - javascript

I'm cloning a row and I want to check in the database if the code exists. This all works fine on the first row but not on the cloned rows. I have an idea that I have to make the id of the field unique, I have tried to add the the code that checks if the code exist to the add button event but it doesn't work. Can someone please tell me how to merge the two script so it works on the cloned rows.
Code:
HTML
<table>
<tr id="show_codes">
<td colspan="2" class="text-fields" align="center" valign="middle">
<div class="codeForm">
<table class="codeForm" align="left" width="500px" cellpadding="0" style="padding-left: 20px;" cellspacing="0">
<tr>
<td height="15px">Codes that exist is 0011, 1234</td>
</tr>
<tr class="code_row">
<td class="details-border1" height="40px" valign="middle" bgcolor="#f3f3f3" align="center">
<input id="code" value="" class="text ui-widget-content ui-corner-all" type="text" name="code[]" />
<div id="status"></div>
</td>
<td class="details-border2" bgcolor="#f3f3f3" align="center">
<input value="" class="text ui-widget-content ui-corner-all" type="text" name="value[]" />
</td>
<td class="borders-right-bottom" bgcolor="#f3f3f3" align="center">
<input type="button" class="btnDeleteCode" value="Delete" />
</td>
</tr>
</table>
</div>
<table width="500px" align="left">
<tr>
<td align="right"><span style="cursor: pointer; color: #007FC6; font-weight: bold;" id="btnAddCode" value="add more">Add another code</span>
</td>
</tr>
</table>
</td>
</tr>
JQUERY
var dom = {};
dom.query = jQuery.noConflict(true);
dom.query(document).ready(function () {
var clonedRow = dom.query('.code_row').clone().html();
var appendRow = '<tr class = "code_row">' + clonedRow + '</tr>';
var counter = 0;
dom.query('#btnAddCode').click(function () {
dom.query('.codeForm tr:last').after(appendRow);
counter++;
$('.codeForm tr:last input[type="text"]').attr('id', 'code[' + counter + ']');
$('.codeForm tr:last').find('input').val('');
});
dom.query('.btnDeleteCode').live('click', function () {
var rowLength = dom.query('.code_row').length;
if (rowLength > 1) {
deleteRow(this);
} else {
dom.query('.codeForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode) {
dom.query(currentNode).parent().parent().remove();
}
});
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
pic2 = new Image(16, 16);
pic2.src = "tick.gif";
dom.query(document).ready(function () {
dom.query("#code").change(function () {
var usr = dom.query("#code").val();
if (usr.length >= 4) {
dom.query("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
alert(usr);
dom.query.ajax({
type: "POST",
url: "setup_practice_preference_check_code.php",
data: "username=" + usr,
success: function (msg) {
dom.query("#status").ajaxComplete(function (event, request, settings) {
if (msg == 'OK') {
dom.query("#code").removeClass('object_error'); // if necessary
dom.query("#code").addClass("object_ok");
dom.query(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
alert('msg');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
dom.query(this).html(msg);
}
});
}
});
} else {
dom.query("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
}
});
});
Fiddle
Thanks

Related

My validation does not work on added rows and autonumbering

I have a function where i can add rows and autonumbering. The add rows works when you click the "add row" button, and auto numbering works when you press Ctrl+Enter key when there's 2 or more rows. My problem is, my validation does not work on my autonumbering.
For example: when I type manually the "1" on the textbox, it works.
But when I do my auto numbering, "Not good" does not appear on my 2nd
textbox.
Is there anything I missed? Any help will be appreciated.
//this is for adding rows
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
const inputs = document.querySelectorAll(".form");
document.querySelectorAll(".form")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You can call your event handler i.e : change whenever you change your input values by auto numbering . So , use $(this).trigger("change") where this refer to input where value is changed .
Demo Code :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
$(document).on('keyup', '.form', function(e) {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
//loop through all values...
$(".form").each(function(i) {
if (i !== 0) {
$(this).val(++value); //assign new value..
$(this).trigger("change") //call your change event to handle further...
}
})
}
})
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

$(.class).click(function(){}) not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am facing problem in $(.class).click(function(){}); which is not working with my code.
Can any one help me on this.
My code is:
whenever i click on edit button popup div open but since click event not fire so text boxes in popup not filled due to which i am not able to update the record.
Please help me to resolve the issue:
$(document).ready(function(){
$(".btn-ed").click(function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
$("#btnUpdate").click(function() {
var id = $('#txtId').val();
var status = $("#ddlStatus").val();
$.ajax({
cache: false,
type:"post",
url:"updateClass.php",
data: {cId: id, cStatus: status},
success:function(ret){
if(ret=='1')
{
location.reload(true);
window.location="?u=1&#close";
}
else
{
location.reload(true);
window.location="?u=0&#close";
}
}
});
});
});
$(document).ready(function(){
try{
getClassData();
var res = GetParameterValues('u');
var res1='';
if(res)
{
res1 = res.split('#')[0];
if(res1=='1')
{
$("#msg-inf").hide();
$("#msg-fail").hide();
$("#msg-sucess").show();
}
else
{
$("#msg-inf").hide();
$("#msg-fail").show();
$("#msg-sucess").hide();
}
}
}
catch(er){alert(er);}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
function getClassData(){
$.ajax({
cache: false,
type:"post",
url:"classdata.php",
datatype: 'json',
data: {qry: 'ClassData'},
success:function(ret){
var jobj = $.parseJSON(ret);
loadTable(jobj);
}
});
}
function loadTable(dt){
try{
var dLength = dt.length;
var tableData = '';
if(dLength > 0){
for(var i=0;i < dLength; i++){
tableData += "<tr class='data'><td class='data' width='30px'>"+dt[i].id+"</td><td class='data' width='70px'>"+dt[i].class_name+"</td><td class='data' width='70px'>"+dt[i].school_name+"</td><td class='data' width='60px'>"+(dt[i].is_active=='1'?'Active':'Deacive')+"</td><td class='data' width='70px'><a href='#openModal'><button id='button' class='btn-ed'>Edit</button></a></td></tr>";
}
$("#tblClass").append(tableData).show();
}
}
catch(err){alert(err);}
}
});
and HTML
<body>
<?php
include 'header.php';
?>
<div id="wrapper">
<?php include 'left-sidebar.php'; ?>
<div id="rightContent">
<h3>Classes</h3>
<div><div class='informational' id="msg-inf">To update status of any class click on Edit button.</div>
<div class='failure' id="msg-fail" style="display:none;">Class status changing failed due to some error.</div>
<div class='success' id="msg-sucess" style="display:none;">Class status successfully changed. Reload page to view changes</div>
</div>
<table class="data" id="tblClass" style="display:none;">
<tr class="data">
<th class="data" width="30px">No</th>
<th class="data" width="70px">Class Name</th>
<th class="data" width='70px'>School Name</th>
<th class="data" width='60px'>Status</th>
<th class="data" width="70px">Action</th>
</tr>
<!--<tr class="data">
<td class="data" width="30px"><?php echo $row['id'];?></td>
<td class="data" width="70px"><?php echo $row['class_name'];?></td>
<td class="data" width="70px"><?php echo $row['school_name'];?></td>
<td class="data" width="60px"><?php echo $status;?></td>
<td class="data" width="70px">
<button id="button" class="btn-ed">Edit</button>
</td>
</tr>-->
</table>
</div>
<div class="clear"></div>
<!-- modal dialog div --->
<div id="openModal" class="modalDialog">
<div> X
<h2>Update Class Status</h2>
<div style="text-align:center;">
<table width="100%">
<tr>
<td>Id</td>
<td><input type="text" id="txtId" disabled="true"></td>
</tr>
<tr>
<td>Class:</td>
<td><input type="text" id="txtClass" disabled="true"></td>
</tr>
<tr>
<td>School</td>
<td><input type="text" id="txtSchool" disabled="true"></td>
</tr>
<tr>
<td>Status</td>
<td><select id="ddlStatus"><option value="1">Active</option><option value="0">Deactive</option></select></td>
</tr>
<tr><td></td>
<td>
<button id="btnUpdate" class="button">Update</button>
Cancel
</td>
</tr>
</table>
</div>
</div>
</div>
Thanks in advance..
When dynamically adding an element to the DOM, you cannot attach an event handler to it on document.ready. You need to redefine you event handler to the document, and "look" for the element instead.
The handler should be:
$(document).on('click', '.btn-ed', function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
You can try this:
$(document.body).on('click', '.btn-ed' ,function(e){
// your code
});

JQuery function is not being called

Below is my HTML code to handle, on click of id, it has to call javascript function viewLineActionURL and then to controller. Both of the alerts are coming, but still it is not calling the controller modifyLine method.
<script>
var viewLineActionURL;
$(document).ready(function() {
viewLineActionURL = function(obj) {
alert('view*' + obj + '*');
$("#formname").attr("action",obj); // To Controller
alert('false..');
};
});
</script>
<table class="tg" id="pResultsjoin">
<thead align="left">
<tr>
<th class="tg"><input type="checkbox" id="all" disabled="disabled" onclick="toggle(this);" /></th>
<th class="tg">Person Id#</th>
<th class="tg">Age</th>
</tr>
</thead>
<tbody align="left">
<tr th:each="map : ${list}">
<td class="tg bg"><input type="checkbox" class="checkboxclass" name="check" th:value="${map['PID']}" /></td>
<td class="tg bg em" th:id="${map['PID']}" th:name="${map['PID']}" th:text="${map['PID']}" th:onclick="'javascript:viewLineActionURL(\'' + #{/LineController/modifyLine} + '\')'" ></td>
<td class="tg bg" th:text="${map['AGE']}"></td>
</tr>
</tbody>
</table>
But I have this below similar code working:
Button:
<input type="submit" value="Modify" class="btn btn-primary" id="modifyLine" th:onclick="'javascript:modifyLineActionURL(\'' + #{/LineController/modifyLine} + '\')'" />
Javascript:
modifyLineActionURL = function(obj) {
if ($('.checkboxclass:checked').length == 1) {
$("#formname").attr("action",obj);
} else if ($('.checkboxclass:checked').length > 1) {
alert('Please select only one quotation line');
} else {
alert('Please select a quotation line');
}
};
Can anyone help on this issue

JQuery with .live & .remove I can't figure this out

Here is a jsfiddle that is working except for the function I'm trying to figure out.
I have this code that .appends a .table to a form on a value change in the .qty field. I'm trying to figure out 2 things.
The first is that only ONE extra line may be available at any time.
The second would be to remove that one extra line when the #extraDiscount has .focusin.
Here's the JQuery.
var TheOrderLine = ('<table class="orderLine formFont" width="400" hspace="0" vspace="0"><tr><td width="75" valign="top">Name:<input class="ProductName" type="text" size="6"></td><td width="75" valign="top">WholeSale:<input class="WholeSalePrice" type="text" size="6"></td><td width="75" valign="top">QTY:<input class="qty addLine" type="text" size="6"></td><td width="75" valign="top">L/Total:<input class="lineTotal" type="text" size="6"><br></td><td width="100" valign="top"><div id="delButton">DEL</div></td></table>');
$(document).ready(function(e) {
//This adds the Line Totals
});function updateTotal() {
var totalA = 0;
$('.lineTotal').each(function() { totalA += parseFloat($(this).val()) || 0; });
$('#productTotals').val(totalA.toFixed(2));
}
//This is the autocomplete and is working fine
$(function() {
$('.ProductName').val("");
$('.WholeSalePrice').val("");
$(document).ready(function(e) {
$('.ProductName').live({
focusin: function() {
$(this).autocomplete({
source: "PRODUCT.SEARCH.QUERY.php",
minLength: 2,
autoFocus: true,
select: function(event, ui) {
var $tr = $(this).closest('tr');
$tr.find('.ProductName').val(ui.item.ProductName);
$tr.find('.WholeSalePrice').val(ui.item.WholeSalePrice);
}
})
}
});
});
});
// Used a CSS button for the Delete line
$("#orderFormDiv_Lines").delegate("#delButton", "click", function () {
$(this).closest('.orderLine').remove();
updateTotal(); /* this recalculates the total after an item is deleted */
});
// Removes all lines
$("#removeAll").click(function () {
$('.orderLine').remove();
$('#productTotals input[type="text"]').val('');
updateTotal();
});
$(document).ready(function(e) {
$('.qty').live({
change: function() {
/* This add the numbers for lineTotal field */
var qty = $(this).val();
var $tr = $(this).closest('tr');
var WholeSalePrice = $('.WholeSalePrice:eq(0)', $tr).val();
var lineTotal = parseFloat(qty * WholeSalePrice) || 0;
$('.lineTotal:eq(0)', $tr).val(lineTotal.toFixed(2));;
updateTotal();
// this is the line that I need to add the if function on but I can't figure out how to find the extra empty table rows that may exist and also not let
$('#orderFormDiv_Lines').append(TheOrderLine);
// I'm thinking something along this line here but I can't grasp the .live concept for grabbing the empty .orderlines.
/*
if ('.orderLine':empty) && > 1; {
$('.orderLine').remove();
} else {
$('#orderFormDiv_Lines').append(TheOrderLine);
}
*/ }
})
// Added this in case the Delete All button is used.
$('#addLine').click(function(){
$('#orderFormDiv_Lines').append(TheOrderLine);
});
});
Here's HTML form....
<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<hr>
<form action="<?php echo $PHP_SELF;?>" method="post">
<div id="orderFormContent">
<div id="orderFormDiv_Lines">
<table class="orderLine formFont" width="400" hspace="0" vspace="0">
<tr>
<td width="75" valign="top">
Name:<input class="ProductName" type="text" size="6"></td>
<td width="75" valign="top">
WholeSale:<input class="WholeSalePrice" type="text" size="6"></td>
<td width="75" valign="top">
QTY:<input class="qty addLine" type="text" size="6"></td>
<td width="75" valign="top">
L/Total:<input class="lineTotal" type="text" size="6"><br></td>
<td width="100" valign="top">
<div id="delButton">DEL</div>
</td>
</table>
</div>
<div id="orderFormDiv_BottomRight"><br>
<table width="100%" border="1">
<tr>
<td>#extraDiscount</td>
<td><input id="extraDiscount" type="text" size="10"></td>
</tr>
<tr>
<td>#totalDiscounts</td>
<td><input id="totalDiscounts" type="text" size="10" disabled></td>
</tr>
<tr>
<td>#productTotals</td>
<td><input id="productTotals" type="text" size="10" disabled></td>
</tr>
</table></div>
<br>
<p class="clear"/>
</div>
<div id="removeAll">Delete All</div><br><br>
<div id="addLine">Add Line</div>
<hr>
<br></div>
</form><hr>
</body>
</html>
Any help would be AWESOME!!! Thanks!
to limit appending only 1 line for .orderLine change your click function to
$('#addLine').bind('click', function(){
if($('.orderLine').length == 0)
$('#orderFormDiv_Lines').append(TheOrderLine);
});
and to remove the line when discount is focused :
$('#extraDiscount').bind('focus', function(){
$('#orderFormDiv_Lines table').each(function(){
var hasInput = false;
$(this).find('input').each(function(){
if($(this).val() != '')
hasInput = true;
});
if(!hasInput) $(this).remove();
});
});

Categories

Resources