My validation does not work on added rows and autonumbering - javascript

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>

Related

Dynamic autonumbering when ctrl + hit enter

I have an autonumbering function. If control + enter are pressed, it'll do an auto numbering function. The autonumbering function works now, but it has an error. When i start my autonumbering at the second textbox, the first textbox is affected too. My target is when i change only the 2nd or 3rd textbox, the textbox before them shouldn't change the value.
Please, see the image i provided for better explanation. Also, I provided a JSFIDDLE
//this is my function for autonumbering
const inputAncestor = document.querySelector("tbody");
inputAncestor.addEventListener("keyup", e => {
if (
e.target.matches('input.form-control') &&
((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10))
) {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
inputs.forEach((inp) => {
if (inp !== e.target) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic 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" value="' + rowIndexx + '" /></td>"' +
'<td><input name="test1' + rowIndex + '" value="" class="form-control" type="number" /></td>"' +
'<td><input id="test' + rowIndex + '" name="test' + rowIndex + '" type="number" /></td>"' +
'<td><input id="test' + rowIndex + '" name="test' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
<th>#</th>
<th>auto numbering ctrl+ enter</th>
<th>col1#</th>
<th>col2 #</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="test1" class="hehe" type="number" />
</td>
<td class="labelcell">
<input name="test2" class="hehe" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=5><button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

I want to add new data from second table to main table

I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>

ajax, php how to save correctly data

I tried to send information via ajax about user_question and language input fields, but how to write correctly this element inside ajax javascript to save the table element value in database.
thank you.
the script element.
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '</td>
<td class="col-md-2">' . HTML::inputField('language', null, 'placeholder="Language"') . '</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// element pb
// var data = $("#new_product").serialize(); // form id or table id ?
var dataString = 'user_question='+user_question+'language='+language;
$.ajax({
type: 'POST',
url: '{$ajax_url}',
data : dataString,
success: function(data) {
alert(data);
$("p").text(data);
}
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
Use like this to get php variables value inside javascript in .php page
url: "<?php echo $ajax_url; ?>",
Also use & and symbol to add two or more param in your dataString

When tabout event get fire i want to add new row under current row .But combo box does not load?

Html code:
Below image describes my output.Please kindly some one help me to resolve this issue.
<table class="table table-striped table-bordered table-hover table-condensed tableSiteUser">
<thead>
<tr>
<th>#</th>
<th>SiteName</th>
<th>UserName</th>
<th>Channel</th>
<th>Action</th>
</tr>
</thead>
<tbody id="site-table-body">
<tr>
<td class="countsiteuser">1</td>
<td><select class="form-control" id="siteContainer"></select>
</td>
<td><input type="checkbox" value="user" id="checkboxbutton"><input type="text" class="and" disabled placeholder="Default"/></td>
<td><input type="text" class="form-control" placeholder="Enter the Channel"/></td>
<td><span class="form-control glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>
JavaScript:
$('.tableSiteUser').on('keydown','td:nth-child(4)',function(e){
var keyCode=e.keyCode || e.which;
if(keyCode == 9){
serialUserSite++;
$('tbody#site-table-body').append('<tr>'
+'<td class="beer" contenteditable="false">'+serialUserSite+'</td>'
+'<td><select class="form-control" id="siteContainer">'
+'</select></td>'
+'<td><input type="checkbox" value="user" id="checkboxbutton"><input type="text" class="and" disabled placeholder="Default"/></td>'
+'<td><input type="text" class="form-control" placeholder="Enter the Channel"/></td>'
+'<td><span class="glyphicon glyphicon-trash form-control"></span></td>'
+'</tr>');
}
});
ajax code:
$.ajax({
url : "http://localhost:8080/IDNS_Rule_Configuration/idns/systemData/getAllSites",
type : "GET",
contactType : "application/json",
dataType : "json",
success : function(data){
for(var i=0;i<data.length;i++){
var dataId = data[i].siteId;
var dataArray = data[i].siteName;
$('#siteContainer').populate(dataId, dataArray);
}
}
});
populate jquery code:
$.fn.populate = function(dataId, dataArray) {
var $selectbox = $(this);
// check if eleme nt is of type select
if ($selectbox.is("select")) {
//for (var i = 0; i < dataId.length; i++) {
$selectbox.append('<option value="' + dataId
+ '" stream="' + dataId + '">'
+ dataArray + '</option>');
//}
}
};
This is my output ,site name combo box is loaded from db.In first row it works .At second row it does not work

AJAX: add new row to table or remove using AJAX

This is the logic:
I input something to form, and the form is AJAX live search. after I found value, I click on add button and it creates new row in existing table / tbody.
<table class="standard">
<thead>
<tr>
<td colspan="2">
Start Input barcode / Product Name
</td>
<td colspan="4">
<input type="text" size="90" value="" placeholder="Barcode / Product Name">
</td>
<td>
<button class="tambah"><i class="icon-plus"></i> Add</button>
</td>
</tr>
<tr>
<td>
No.
</td>
<td>
Kode Barang
</td>
<td>
Nama Barang
</td>
<td>
Qty
</td>
<td>
Harga
</td>
<td>
Disc %
</td>
<td>
Total
</td>
</tr>
</thead>
<tbody>
<!-- when button add is click that will add <tr></tr> here -->
</tbody>
</table>
can i do that? if so, how?
Fiddle Example: http://jsfiddle.net/anggagewor/cauPH/
You can find the pseudo code below.
$('#button_id').on('click', function(e) {
$.ajax({
url : yourUrl,
type : 'GET',
dataType : 'json',
success : function(data) {
$('#table_id tbody').append("<tr><td>" + data.column1 + "</td><td>" + data.column2 + "</td><td>" + data.column3 + "</td></tr>");
},
error : function() {
console.log('error');
}
});
});
Try this
var scntDiv = $('#p_scents');
var i = $('#p_scents tr').size() + 1;
$('#addScnt').click(function() {
scntDiv.append('<tr><td><select name="type" id="type"><option value="Debit">Debit</option><option value="Credit">Credit</option></select></td><td><select name="accounts" id="accounts"><option value="">SELECT</option><option value="One">One</option><option value="Two">Two</option></select></td><td><input type="text" name="debit_amount" id="debit_amount"/></td><td><input type="text" name="credit_amount" id="credit_amount"/></td><td>Remove</td></tr>');
i++;
return false;
});
//Remove button
$(document).on('click', '#remScnt', function() {
if (i > 2) {
$(this).closest('tr').remove();
i--;
}
return false;
});​
Here's a working example, including remove row functionality: DEMO.
$("<tr><td>.....content...<td><a class='remove'>remove</a>").appendTo("#tableid tbody").find('.remove').click(function () {
$(this).parent().parent().remove();
});
In your ajax response you can do this
$("#myTable > tbody").append('<tr><td>my data</td><td>more data</td></tr>');
'#myTable' will be replaced by your table id or class and <td>my data</td><td>more data</td> will be replaced by your content

Categories

Resources