Dynamically row validation not working - jquery? - javascript

I trying to validate dynamically added rows but some faults its not working.
I could'nt find my problem.
Anyone tell me or correct me why its not working n all..
I need to validate dynamically add rows and columns.
Here is my full code..
Full code Fiddle <3
Here is my sample code..
$(document).ready(function() {
$("#ok_button").on("click", function() {
$(".act").val($("#cash_text:first").val());
});
$("#add_Row").on("click", function() {
var counter = 0;
var idVal = $('#tab_logic tr:last').find('td:first').html();
// alert(idVal);
if (idVal === undefined) {
counter = 0;
} else {
var matches = idVal.match(/\d+/g);
// alert(matches);
if (matches != null) {
counter = Number(matches) + counter + 1;
}
}
var newRow = $("<tr>");
var cols = "";
if ($('.price').length > 0) {
var first_ele = document.querySelector('.price').value;
} else {
var first_ele = '';
}
cols += '<td><select class="form-control sel_sel status required" id="accountName' + counter + '" name="accountName" for="accountName" required><option value="">Choose an account</option><option value="1">code 1</option></select></td>';
cols += '<td><input value="' + first_ele + '" type="text" class="form-control required price narr" name="narr" placeholder="Enter your text here" id="acc_narrat' + counter + '" data-toggle="modal" data-target="#narratModal"/></td>';
cols += '<td><input type="number" class="form-control sumTot deb allignAmt" id="cashdeb' + counter + '" min="0" data-action="sumDebit" name="debit" placeholder="Debit amount" onkeypress="restrictMinus(event);" required/></td>';
cols += '<td style="width: 11%;"><button type="button" class="adRow ibtnDel" style="width:30%;position: relative;right: 25%;">x</button></a></td>'
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
if ($("#tab_logic tbody tr").length == 1)
$("#cash_text:first").val('');
evaluateTotal();
});
});
// dynamic row validations
$(document).ready(function() {
$('#contactForm').on('submit', function(event) {
console.log($('.narr'))
$('.status').each(function() {
$(this).rules("add", {
required: true
})
});
$('.narr').each(function() {
$(this).rules("add", {
required: true
})
});
$('.deb').each(function() {
$(this).rules("add", {
required: true
})
});
event.preventDefault();
if ($('#contactForm').validate().form()) {
alert("validates");
} else {
alert("does not validate");
}
});
$('#contactForm').validate();
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- validation cdn -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/css/bootstrapValidator.min.css">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>
<form id="contactForm">
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
<table class="table table-bordered table-hover order-list" id="tab_logic" style="width:100% !important">
<thead>
<tr style="background-color: #680779; color: #fff;">
<th class="text-center">
select code*
</th>
<th class="text-center">
description*
</th>
<th class="text-center">
amount*
</th>
<th class="text-center">
action*
</th>
</tr>
</thead>
</table>
<!-- submit button -->
<div class="form-group col-4 vocSub" style="margin-bottom: 0px !important;">
<div class="col-md-12 cashform_submit" id="">
<input type="submit" class="btn add-btn submit-btn load cashmainBtn" id="cashSub" value="Submit" />
</div>
</div>
</form>
I need to validate dynamically add rows and columns.
Thank you

Important points first about the changes:
There was a problem in the implementation of incrementing the counter so I changed it to a working one first. The problem was you get a NaN value for the counter in the succeeding rows so you will not get a unique name for the succeeding rows. I just created a variable outside that will increment every time the add button is clicked.
I am just showing how to make it work. For me, there's a problem with the framework of how it handles the showing of error messages. What I mean is, the name of the input field should be unique so that the error messages are displayed. This will pose a problem for array type fields like your problem on the backend side. I guess you will have to improvise on the backend.
Here is the summarized code snippet:
let counter = 0;
$(document).ready(function() {
$("#add_Row").on("click", function() {
counter++;
...
cols += '<td><select class="form-control sel_sel status required" id="accountName' + counter + '" name="accountName'+counter+'" for="accountName" required><option value="">Choose an account</option><option value="1">code 1</option></select></td>';
cols += '<td><input value="' + first_ele + '" type="text" class="form-control required price narr" name="narr'+counter+'" placeholder="Enter your text here" id="acc_narrat' + counter + '" data-toggle="modal" data-target="#narratModal"/></td>';
cols += '<td><input type="number" class="form-control sumTot deb allignAmt" id="cashdeb' + counter + '" min="0" data-action="sumDebit" name="debit'+counter+'" placeholder="Debit amount" onkeypress="restrictMinus(event);" required/></td>';
...
});
...
});
...
Please take note of the concatenated counter in the name attributes of the dynamic fields.

Related

How can I add an incrementing id="" attribute to the following JavaScript generated HTML form?

I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.
I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><table width="100%"><tr><td><input type="text"
name="field_name[]" value="" class="form-control" style="width:98%;"
placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""
class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>
<a href="javascript:void(0);" class="remove_button"><button type="button"
class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -
Remove </button></a></div>';
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field">
<button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>
</a>
</div>
</div>
You can try this snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1; //Initial field counter is 1
var idCounter = 0;
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
function fieldHTML(id) {
return '<div><table width="100%"><tr><td>id:' + id + '<input type="text"' +
'id="role-' + id + '" name = "field_name[]" value = "" class="form-control" style = "width:98%;"' +
'placeholder = "Role" /></td > <td><input type="text" id="name-' + id + '" name="field_name[]" value=""' +
'class="form-control" style="width:100%;" placeholder="Name" /></td></tr ></table >' +
'<a href="javascript:void(0);" class="remove_button"><button type="button"' +
'class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> - Remove </button></a></div >';
}
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
$(wrapper).append(fieldHTML(idCounter++)); //Add field html
x++; //Increment field counter
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%" />
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%" />
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field"><button
style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role
</button></a>
</div>
</div>
Note, I have created a new variable idCounter to keep the id unique even when you remove a row. Otherwise, it might create elements with duplicate ids.
This is just one quick way, but there are many other ways this can be achieved. The code can be made mode tidy and readable.

Prevent form submission by checking every dynamically created text boxes are empty

Here I am trying to check each and every dynamically created textboxes whether it is empty or not before the form submission.
Here is the HTML code,
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Here is the Ajax code
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
swal({
title: "Are you sure?",
text: "You wanna proceed this Payment!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-success",
confirmButtonText: "Yes, Proceed It!",
closeOnConfirm: false
},
function(isConfirm){
if (!isConfirm) return;
$.ajax({
url: "testquery/test_payments.php", // Url to which the request is send
method: "POST", // Type of request to be send, called as method
data: {
'test_id': test_id,
'amount': amount,
'p_id': p_id,
'pres_id': pres_id,
'description':description
},
success: function (data) {
if (data == 'Password Changed') {
swal("Success", "Invoice has been Generated :)", "success");
} else {
swal("Sorry", "Something Went Wrong. Please try again later:(", "error");
}
},
error: function (data) {
//other errors that we didn't handle
swal("Sorry", "Failed to Proceed. Please try later :(", "error");
}
});
});
};
// check validations
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
if (!$("#test_id").val()) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
});
I want to check the test_id textbox is empty. Before dynamically generating the textboxes there, already there is a row of textboxes including test_id textbox. My problem is, before generated, it check the textbox as empty or not by using function, but after generated it does not check. I don't know where I went wrong.
Please help me may highly appreciated.
Rather than using the elementID use class name to get the collection of elements and iterate through them. the problem we have here is all input have the same id so jquery will return the first element it finds and ignore the rest since with ID we assume that it is unique throughout the DOM
function checkname(el){
}
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
debugger;
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
alert('invoice generated')
};
// check validations
function validateContact() {
debugger;
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
//list of test_id inputs
var testIdList =
document.getElementsByClassName('test_id')
for(let i= 0 ; i<testIdList.length; i++){
if (!testIdList.item(i).value) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
}
return valid;
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Use class, name or other attributes instead id, because you have a several elements with the same ids - it's always create problems. If you need check inputs with class "text_id" before submit try to change validation function
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
$('.text_id').map(function(i, el){
if(!$(el).val() || $(el).val().trim() == '') {
valid = false;
$("#test_id_info").html("(Required)");
$(el).css('background-color', '#FFFFDF');
}
});
return valid;
}

How to get the Sum of Lowest values in 3 rows each added dynamically

The following code will get the lowest value entered in first 3 columns, it is running fine. But after adding the row (Add Row) i am unable to get the lowest value from next 3 columns. Also i want to get the sum of all 3 lowest values from as much columns as user will add. Your kind help is required in this regard.
$(document).ready(function() {
var i = 1;
$("#Add_BDSP").click(function() {
$('#BDSP' + i).html("<td><input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/></td>");
$('#Tab_BDSP').append('<tr id="BDSP' + (i + 1) + '"></tr>');
i++;
});
$("#Delete_BDSP").click(function() {
if (i > 1) {
$("#BDSP" + (i - 1)).html('');
i--;
}
});
});
var input = $('[name="QuotedAmount1[0]"],[name="QuotedAmount2[0]"],[name="QuotedAmount3[0]"]'),
QuotedAmount1 = $('[name="QuotedAmount1[0]"]'),
QuotedAmount2 = $('[name="QuotedAmount2[0]"]'),
QuotedAmount3 = $('[name="QuotedAmount3[0]"]'),
MulRes = $('[name="ServiceTotalCost"]');
input.change(function() {
var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val());
var Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val());
var Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());
MulRes.val(Math.min(Qoute1, Qoute2, Qoute3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-float">
<table class="table table-bordered table-hover" id="Tab_BDSP">
<thead>
<tr>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr id='BDSP0'>
<td>
<input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />
</td>
</tr>
<tr id='BDSP1'></tr>
</tbody>
</table>
</div>
<a id="Add_BDSP" class="btn btn-default pull-left">Add Row</a><a id='Delete_BDSP' class="pull-right btn btn-default">Delete Row</a>
</div>
<div class="col-md-4">
<div class="input-group form-group">
<span class="input-group-addon">
<i class="material-icons">business_center</i>
</span>
<div class="form-line">
<input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
</div>
</div>
</div>
But after adding the row (Add Row) i am unable to get the lowest value
from next 3 columns
Your main problem is:
QuotedAmount1 = $('[name="QuotedAmount1[0]"]'),
QuotedAmount2 = $('[name="QuotedAmount2[0]"]'),
QuotedAmount3 = $('[name="QuotedAmount3[0]"]'),
Because you just select QuotedAmount1[0] to QuotedAmount3[0], after you append row new input has QuotedAmount1[1] .. , also you used change and for new row you need to use change with document selector, to get live change. And you should move your variable inside of change event. Important things is, you should select your input without name, here is working snippet:
$(document).ready(function() {
var i = 1;
$("#Add_BDSP").click(function() {
$('#BDSP' + i).html("<td><input type='text' name='QuotedAmount1[" + i + "]' placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount2[" + i + "]'placeholder='Quoted Amount' class='form-control' /><input type='text' name='QuotedAmount3[" + i + "]' placeholder='Quoted Amount' class='form-control'/></td>");
$('#Tab_BDSP').append('<tr id="BDSP' + (i + 1) + '"></tr>');
i++;
});
$("#Delete_BDSP").click(function() {
if (i > 1) {
$("#BDSP" + (i - 1)).html('');
i--;
}
});
});
$(document).on('change', '#Tab_BDSP tbody tr td input[type="text"]', function() {
let result = 0;
var MulRes = $('input#ServiceTotalCost');
var QuotedAmount1 = $(this).parent().find('input[type="text"]').eq(0),
QuotedAmount2 = $(this).parent().find('input[type="text"]').eq(1),
QuotedAmount3 = $(this).parent().find('input[type="text"]').eq(2);
var Qoute1 = (isNaN(parseInt(QuotedAmount1.val()))) ? 0 : parseInt(QuotedAmount1.val()),
Qoute2 = (isNaN(parseInt(QuotedAmount2.val()))) ? 0 : parseInt(QuotedAmount2.val()),
Qoute3 = (isNaN(parseInt(QuotedAmount3.val()))) ? 0 : parseInt(QuotedAmount3.val());
var min = Math.min(Qoute1, Qoute2, Qoute3);
$(this).parent().attr('data-lowest', min)
$('#Tab_BDSP tbody tr td').each(function() {
result += +$(this).attr('data-lowest')
});
MulRes.val(result)
});
Thank you for kind response,
the code is running perfect,
but the issue is if i change the value in additional rows,
it adds the lowest into the sum,
e.g. 1st row have 300000 400000 500000 and second row have 600000 700000 800000 The total sum will be 900000 which is perfect. but if i change the value from 600000 to 200000 it should shows 700000 but it gives value of 1100000. Your kind help is needed to rectify this issue in the given code. – ADIL I.T 8 mins ago
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-float">
<table class="table table-bordered table-hover" id="Tab_BDSP">
<thead>
<tr>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr id='BDSP0'>
<td>
<input type="text" name='QuotedAmount1[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount2[0]' placeholder='Quoted Amount' class="form-control" required />
<input type="text" name='QuotedAmount3[0]' placeholder='Quoted Amount' class="form-control" required />
</td>
</tr>
<tr id='BDSP1'></tr>
</tbody>
</table>
</div>
<a id="Add_BDSP" class="btn btn-default pull-left">Add Row</a><a id='Delete_BDSP' class="pull-right btn btn-default">Delete Row</a>
</div>
<div class="col-md-4">
<div class="input-group form-group">
<span class="input-group-addon">
<i class="material-icons">business_center</i>
</span>
<div class="form-line">
<input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
</div>
</div>
</div>
Also i want to get the sum of all 3 lowest values from as much columns
as user will add
For get sum you need to get min and also old lowest value
This code works. I just made all of the script run separately so it worked.
$(".input0").keyup(function() {
var val10 = $("[name='a1[0]']").val();
var val20 = $("[name='a2[0]']").val();
var val30 = $("[name='a3[0]']").val();
var lowestValue0 = Math.min(val10, val20, val30);
$("[name='answer[0]']").val(lowestValue0);
$("[name='total']").val(lowestValue0);
});
$(document).keyup(function() {
var sum = "";
$('.inputClass').each(function() {
sum += this.value;
});
$("[name='total']").val(sum);
});
$(document).ready(function() {
var a = "1";
$(".add").click(function() {
$('<div class="valueDiv' + a + '"><input name="a1[' + a + ']" class="input' + a + '" placeholder="Value 1"><input name="a2[' + a + ']" class="input' + a + '" placeholder="Value 2"><input name="a3[' + a + ']" class="input' + a + '" placeholder="Value 3"><br><h5>Lowest Value = <\/h5><input name="answer[' + a + ']" class="inputClass" readonly placeholder="Lowest Value"><hr><\/div>').appendTo("#mainDiv");
$('#scripts').append('<script type="text/javascript" id="script' + a + '">$(".input' + a + '").keyup(function() { var val1' + a + ' = $("[name=\'a1[' + a + ']\']").val(); var val2' + a + ' = $("[name=\'a2[' + a + ']\']").val(); var val3' + a + ' = $("[name=\'a3[' + a + ']\']").val(); var lowestValue' + a + ' = Math.min(val1' + a + ', val2' + a + ', val3' + a + '); $("[name=\'answer[' + a + ']\']").val(lowestValue' + a + '); });<\/script>');
a++;
});
$(".delete").click(function() {
if (a > 1) {
$(".valueDiv" + (a - 1)).remove();
$("script" + (a - 1)).remove();
a--;
}
var sum = "";
$('.inputClass').each(function() {
sum += this.value;
});
$("[name='total']").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div id="mainDiv" style="width: 100%; height: 100%; padding: 50px;">
<div class="valueDiv0">
<hr>
<input name="a1[0]" class="input0" placeholder="Value 1">
<input name="a2[0]" class="input0" placeholder="Value 2">
<input name="a3[0]" class="input0" placeholder="Value 3">
<br>
<h5>Lowest Value = </h5>
<input name="answer[0]" class="inputClass" readonly placeholder="Lowest Value">
<hr>
</div>
</div>
<div style="width: 100%; height: 100%; padding: 0px 50px;">
<h5>Sum of All Lowest Values</h5>
<input style="width: 230px;" name="total" readonly placeholder="Total Value of All Lowest Values">
</div>
<div id="scripts">
</div>
<br>
<div>
<button class="btn btn-primary add">Add Row</button>
<button class="btn btn-danger delete">Delete Row</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

Table rows not visible within <tbody>. How could search filter be implemented in this table?

I'm trying to build a table based on this example: http://demo.webslesson.info/multiple-checkbox-update-data/
https://www.webslesson.info/2018/09/update-multiple-rows-with-checkbox-in-php-using-ajax-jquery.html
It works fine, however I'm struggling with adding a search field to enable search across table rows.
I've tried adding search field, but it didn't work because table rows are not listed within tbody tag, but called dynamically from ajax and not sure what would be the best way to teach my search field to interact with the table rows listed as results from script below. Would someone be able to help me with this? Thanks in advance!
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<form method="post" id="update_form">
<div align="left">
<input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
</div>
<br />
<div class="table-responsive">
<table id="mirror" class="table table-bordered table-striped">
<thead>
<th width="5%"></th>
<th width="20%">Name</th>
<th width="30%">Address</th>
<th width="15%">Gender</th>
<th width="20%">Designation</th>
<th width="10%">Age</th>
</thead>
<tbody></tbody>
</table>
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data- name="'+data[count].name+'" data-address="'+data[count].address+'" data-gender="'+data[count].gender+'" data-designation="'+data[count].designation+'" data-age="'+data[count].age+'" class="check_box" /></td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].address+'</td>';
html += '<td>'+data[count].gender+'</td>';
html += '<td>'+data[count].designation+'</td>';
html += '<td>'+data[count].age+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('click', '.check_box', function(){
var html = '';
if(this.checked)
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-address="'+$(this).data('address')+'" data-gender="'+$(this).data('gender')+'" data-designation="'+$(this).data('designation')+'" data-age="'+$(this).data('age')+'" class="check_box" checked /></td>';
html += '<td><input type="text" name="name[]" class="form-control" value="'+$(this).data("name")+'" /></td>';
html += '<td><input type="text" name="address[]" class="form-control" value="'+$(this).data("address")+'" /></td>';
html += '<td><select name="gender[]" id="gender_'+$(this).attr('id')+'" class="form-control"><option value="Male">Male</option><option value="Female">Female</option></select></td>';
html += '<td><input type="text" name="designation[]" class="form-control" value="'+$(this).data("designation")+'" /></td>';
html += '<td><input type="text" name="age[]" class="form-control" value="'+$(this).data("age")+'" /><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" /></td>';
}
else
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-address="'+$(this).data('address')+'" data-gender="'+$(this).data('gender')+'" data-designation="'+$(this).data('designation')+'" data-age="'+$(this).data('age')+'" class="check_box" /></td>';
html += '<td>'+$(this).data('name')+'</td>';
html += '<td>'+$(this).data('address')+'</td>';
html += '<td>'+$(this).data('gender')+'</td>';
html += '<td>'+$(this).data('designation')+'</td>';
html += '<td>'+$(this).data('age')+'</td>';
}
$(this).closest('tr').html(html);
$('#gender_'+$(this).attr('id')+'').val($(this).data('gender'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"multiple_update.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Data Updated');
fetch_data();
}
})
}
});
});
</script>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("mirror");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Here's an idea for a search field.
After searching a given string, the results will appear in the searchResults div. The script searches through every cell in the tbody element, that hasn't got any child elements - that way the cells with checkboxes are being ignored.
As a search criterion I'm using a simple regular expression, that matches every string that contains the searched value.
Add this part below your form:
<form>
<input id="searchInput" type="text" name="search" />
<button id="searchBtn">Search</button>
</form>
<div id="searchResults"></div>
And this in script tag:
$('#searchBtn').on('click', (e) => {
e.preventDefault()
$('#searchResults').html('')
const searchedVal = $('#searchInput').val()
const tableRows = $('tbody tr')
tableRows.each(row => {
const columns = $(tableRows[row]).find('td')
columns.each(col => {
const columnContent = $(columns[col]).html()
const columnChildren = $(columns[col]).children().length
if (columnChildren > 0) return
const regex = new RegExp('.*' + searchedVal + '.*')
const match = columnContent.match(regex)
match != null && $('#searchResults').append(`<p>Found in row ${row + 1}, column ${col + 1}: ${columnContent}</p>`)
})
})
})

Save dynamic html form data to table (Laravel 5.2)

I have created a dynamic form for making an offer and i don't know how to solve the problem saving that data to a database. I'm using Laravel 5.2 and now i need to make a model and controller....can someone help me please?
How to save this into a database table?
I'm open for hints and tips too, maybe it could be done somehow differently?
This is live form
JSFiddle
<div>
<h1>Angebot</h1>
<form method="POST" action="" accept-charset="UTF-8">
<table id="t1">
<tr>
<th><button type="button" class="addRow">Personal hinzufügen</button></th>
<th>Anzahl</th>
<th>Preis pro Stunde</th>
<th>Stunden</th>
<th>Total</th>
</tr>
<tr id="row0" class="item">
<td><select name="personal" class="select"><optgroup label="Personal">
<option selected="true" disabled="true" style="display:none">--auswählen</option>
<option value="koeche">Köche</option>
<option value="barkeeper">Barkeeper</option>
<option value="garderobiere">Garderobiere</option>
<option value="chauffeure">Chauffeure</option>
<option value="oberkellner">Oberkellner</option>
<option value="serviceleitung">Serviceleitung</option>
<option value="hilfskoch">Hilfskoch</option>
<option value="servicekraefte">Servicekräfte</option>
</optgroup>
</select></td>
<td><input name="anzahl" class="qnty amount" value="" type="number" min="0" step="1"/></td>
<td><input name="preisps" class="price amount" value="" /></td>
<td><input name="stunden" class="hours amount" value="" /></td>
<td><input name="total" class="total" value="" readonly="readonly" /></td>
</tr>
</table>
<br />
<table id="t2">
<tr>
<th>Netto =<br></th>
<th><input id="netto" readonly="readonly" name="netto" type="text" value=""></th>
</tr>
<tr>
<td>Steuer 19% =<br></td>
<td><input id="steuer" readonly="readonly" name="steuer" type="text" value=""></td>
</tr>
<tr>
<td>Brutto =<br></td>
<td><input id="brutto" readonly="readonly" name="brutto" type="text" value=""></td>
</tr>
</table>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
and here is the javascript code
// main function when page is opened
$(document).ready(function () {
// function for adding a new row
var r = 0;
if(r<11){
$('.addRow').click(function () {
r++;
$('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal' + r + '" class="select"><optgroup label="Personal"><option selected="true" disabled="true" style="display:none">--auswählen</option><option value="koeche">Köche</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekraefte">Servicekräfte</option></optgroup></select></td><td><input name="anzahl' + r + '" class="qnty amount" value="" type="number" min="0" step="1"/></td><td><input name="preisps' + r + '" class="price amount" value="" /></td><td><input name="stunden' + r + '" class="hours amount" value="" /></td><td><input name="total' + r + '" class="total" value="" readonly="readonly" /></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
});
// remove row when X is clicked
$(document).on("click", ".btn_remove", function () {
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
// calculate everything
$(document).on("keyup", ".amount", calcAll);
}
});
// function for calculating everything
function calcAll(event) {
// calculate total for one row
$(".item").each(function () {
var qnty = 1;
var price = 1;
var hours = 1;
var total = 1;
if (!isNaN(parseFloat($(this).find(".qnty").val()))) {
qnty = parseFloat($(this).find(".qnty").val());
}
if (!isNaN(parseFloat($(this).find(".price").val()))) {
price = parseFloat($(this).find(".price").val());
}
if (!isNaN(parseFloat($(this).find(".hours").val()))) {
hours = parseFloat($(this).find(".hours").val());
}
total = qnty * price * hours;
$(this).find(".total").val(total.toFixed(2));
});
// sum all totals
var sum = 0;
$(".total").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
// show values in netto, steuer, brutto fields
$("#netto").val(sum.toFixed(2));
$("#steuer").val(parseFloat(sum * 0.19).toFixed(2));
$("#brutto").val(parseFloat(sum + parseFloat(($("#steuer").val()))).toFixed(2));
}
// replace , with . and block writing letters
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumericOnly')){ return; }
$(this).data('forceNumericOnly', true);
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
});
};
// execute function on element focus
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
For the first question
1) you added "r" variable for rows limit in wrong place so add like below
var r = 1;
$('.addRow').click(function () {
if(r<10)
{
r++;
$('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal' + r + '" class="select"><optgroup label="Personal"><option selected="true" disabled="true" style="display:none">--auswählen</option><option value="koeche">Köche</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekraefte">Servicekräfte</option></optgroup></select></td><td><input name="anzahl' + r + '" class="qnty amount" value="" type="number" min="0" step="1"/></td><td><input name="preisps' + r + '" class="price amount" value="" /></td><td><input name="stunden' + r + '" class="hours amount" value="" /></td><td><input name="total' + r + '" class="total" value="" readonly="readonly" /></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
}
});
// remove row when X is clicked
$(document).on("click", ".btn_remove", function () {
r--;
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
after above change you will add only 10 row in the table.
2) Question you need to create one json from the created table structure and pass that json in the server side through ajax and in server side parsing your json and store that information in the database.
And from the table design look like it will be 2 table one table have master information and another detail table which have detail information.
Please let me know if you need sample code for that.

Categories