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>
Related
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>
The above screenshot shows the actual correct form. For getting this I tried the below code. My <td> contains a heading as well as a subpoint, which are added dynamically. On click of the Submit button, I want to read the heading & subpoint corresponding to that heading. The data format is given below.
I'm adding the rows dynamically with the header and the data respectively. I'm trying to gather the data in an object before sending the data to the server via AJAX. I'm not able to read the data in the given format.
HTML CODE
<div class="container-fluid">
<h4>Scorecard Metrics</h4>
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<div class="button-bar">
<button class="btnn btnn--pill add-point">Add Sub-Point</button>
<button class="btnn btnn--pill add-heading">Add Heading</button>
</div>
<div class="table-responsive-sm">
<table id="table-scorecard_co" class="table table-bordered">
<thead>
<tr>
<th style="width: 100px!important;" rowspan="2">Metrics</th>
<th style="width: 92px!important;" rowspan="2">Weightage</th>
<th colspan="4" scope="colgroup">Target</th>
<th style="width: 85px!important;" rowspan="2">Actions</th>
</tr>
<tr>
<th>L1</th>
<th>L2</th>
<th>L3</th>
<th>L4</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display: none;">
<a class="plus" title="Plus" ><i class="material-icons"></i></a>
<a class="update" title="Update" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="destroy" title="Destroy"><i class="material-icons"></i></a>
</td>
<td style="display: none;">
<a class="add" title="Add" ><i class="material-icons"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a class="delete" title="Delete"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="button-bar">
<button class="btnn btnn--pill submit" id="Scoresubmit">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- #/ container -->
</div>
JAVASCRIPT CODE
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
var menubar = $("table td:nth-last-child(2)").html();
$(".add-heading").click(function(){
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index();
var row = '<tr class="heading">' +
'<td id="HeadingLabelScorecard" colspan="3"><span id="label_hide" class="heading_label">Heading</span><input id="heading_label_input" class="heading_label-box" type="text" class="form-control"></td>' +
'<td id="HeadingLabelScorecard" colspan="2"><span id="label_hide2" class="heading_weight-label">Total Weightage</span><input class="Tweightage" id="wei'+(wei) + '" type="number" ></td>' +
'<td colspan="1"><span id="label_hide3" class="heading_labelCheckbox">Divide Weightage</span><input class="heading_checkbox" name="Dividecheckbox" id="heading_checkbox" type="checkbox">' +
'<td style="text-align:center;">' + actions + '</td>' +
'</tr>';
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
wei ++;
});
$(".add-point").click(function(){
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index(); //TO ADD ROW AS LAST Child
var lastCheckBox = $('[name="Dividecheckbox"]:last').prop("checked"); //get status of last checkbox
if(lastCheckBox==false){
//Enable row
var row = '<tr class="Parameters" style="text-align: center;">' +
'<td><input class="subpoint_label-box" type="text" class="form-control"id="metrics'+(unique_id) + '"></td>' +
'<td><input disabled class="subpoint_weightage2" id="weightage'+(unique_id) + '" type="number" ></td>' +
'<td><input class="slider_min-value" type="text" id="ex0n'+i+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="ex'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="ex1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="lx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="lx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="lx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="zx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="zx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="zx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="yx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="yx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="yx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td width="20">' + menubar + '</td>' +
'</tr>';
}
else if(lastCheckBox==true){
var row = '<tr class="Parameters" style="text-align: center;">' +
'<td width="20"height="50"><input class="subpoint_label-box" type="text" class="form-control"id="metrics'+(unique_id) + '"></td>' +
'<td width="20"><input class="subpoint_weightage" id="weightage'+(unique_id) + '" type="number" ></td>' +
'<td><input class="slider_min-value" type="text" id="ex0n'+i+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="ex'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="ex1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="lx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="lx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="lx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="zx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="zx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="zx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td><input class="slider_min-value" type="text" id="yx0n'+(i)+'" value="20"><b id="percentage">%</b><input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="yx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="yx1n'+(i)+'" value="80"><b id="percentageMax">%</b></td>' +
'<td width="20">' + menubar + '</td>' +
'</tr>';
}
else{
alert("Please Add Heading!!");
}
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".plus, .update").toggle();
$('[data-toggle="tooltip"]').tooltip();
$("#ex"+unique_id).slider({});
$("#ex"+unique_id).on("slide", function(slideEvt) {
var nid=$(this).attr('name');
$("#ex0"+nid).val(slideEvt.value[0]);
$("#ex1"+nid).val(slideEvt.value[1]);
});
$("#lx"+unique_id).slider({});
$("#lx"+unique_id).on("slide", function(slideEvt) {
var nid=$(this).attr('name');
$("#lx0"+nid).val(slideEvt.value[0]);
$("#lx1"+nid).val(slideEvt.value[1]);
});
$("#zx"+unique_id).slider({});
$("#zx"+unique_id).on("slide", function(slideEvt) {
var nid=$(this).attr('name');
$("#zx0"+nid).val(slideEvt.value[0]);
$("#zx1"+nid).val(slideEvt.value[1]);
});
$("#yx"+unique_id).slider({});
$("#yx"+unique_id).on("slide", function(slideEvt) {
var nid=$(this).attr('name');
$("#yx0"+nid).val(slideEvt.value[0]);
$("#yx1"+nid).val(slideEvt.value[1]);
});
unique_id++
i++
});
WHAT I TRIED TO GET THE DATA
$('#Scoresubmit').click(function () {
GetCoScoreCard();
//ajax calll
});
function GetCoScoreCard() {
$('#scorecard_co .heading').each(function () { //tr
var TotalWeightage;
var item = $(this).closest("tr").find('td');
$.each(item, function (key, value) { //Heading
if (key == 0) {
Heading1 = ($(value).text());
this.Heading1 = Heading1;
}
else if (key == 1) {
TotalWeightage = ($(value).text());
}
else if (key == 2) {
lastCheckBox = $('[name="Dividecheckbox"]:last').prop("checked");
}
});
var parametername, param_Weightage;
$('#scorecard_co .Parameters').each(function () { //td //parameters
var item2 = $(this).closest("tr").find('td');
$.each(item2, function (key, value) {
datalist = ($(value).text());
if (key == 0) {
parametername = ($(value).text());
}
if (key == 1) {
param_Weightage = ($(value).text());
}
if (key == 2 || key == 3 || key == 4 || key == 5)
{
var res = datalist.substring(1, 3);
var res2 = datalist.substring(6, 8);
var key1 = 'L' + i;
MyLevels[key1] = res + "," + res2;
i++;
}
});
parameters = {
"Name": parametername,
"Weightage": param_Weightage,
"Levels": MyLevels, //array
}
paramarray.push(parameters); //paramNewArray
MyLevels = {};
i = 0;
});
metrics={
'Heading':Heading1,
'TotalWeitage': TotalWeightage, //metrics heading and parameters
'DivideWeightage': lastCheckBox,
'parameters': paramarray // paramNewArray
//work in process
}
var stringyfydata = JSON.stringify(metrics);
data1.push(stringyfydata); alert("Title=" + data1);
console.log(data1);
data = {};
parameters = {};
i = 0;
});
}
EXPECTED DATA OUTPUT
[
{"Heading":"SchduleAdherence","TotalWeitage":"20","DivideWeightage":true,"parameters":{"Name":"Scrunity","Weightage":"30","Levels":{"L1":"20,80","L2":"20,80","L3":"20,80","L4":"20,80"}}]},
{"Heading":"Attendence","TotalWeitage":"30","DivideWeightage":true,"parameters":{"Name":"self","Weightage":"30","Levels":{"L1":"20,80","L2":"20,80","L3":"20,80","L4":"20,80"}}]}
]
There are two classes (.Heading = to read the heading, e.g. attendance & another is .Parameter = to read the sub-points), my issue is that every time I try to loop through the data, all the parameters are getting added repeatedly in my object.
you need to re initialize your variable in go score code;
function GetCoScoreCard() {
paramArray = [];
data1 = [];
.....
.....
}
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>
I can add more skills by clicking +Add Skill Button
How can i validate sum to 100 by query.
I want to know how to call the id of the skills and weightage..?
My Form code is this:
<div class="col-lg-12">
<h4>Skills Required</h4>
<div class="col-md-10">
<table id="jobSkills" class="col-lg-10" style="border:1px;">
<tbody>
<tr>
<td class="col-xs-4">Skill</td>
<td class="col-xs-4">Weightage</td>
<td class="col-xs-4">Test Type</td>
<td class="col-xs-4">Assign to GD-Skill</td>
<td class="col-xs-4">Assign to PI-Skill</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-2">
<span class="text-center btn btn-danger addSkills">+ Add Skills</span>
</div>
</div>
Here is my script of addmore
var skillcount=0;
$(".addSkills").click(function(){
$('#jobSkills tr:last').after('<tr>
<td class="col-xs-4"><input class="wp-form-control searchskill" count="' + skillcount + '" name="skill[' + skillcount + '][title]" type="text" autocomplete="off"></td>
<td class="col-xs-4"><input class="wp-form-control" count="' + skillcount + '" name="skill[' + skillcount + '][weightage]" type="text" autocomplete="off"></td>
<td class="col-xs-2"><span class="removeSkill" id="' + skillcount + '" ><a style="color:red">Remove</a></span></td>
</tr>');
skillcount++;
//console.log(skillcount);
});
$("#jobSkills").on('click','.removeSkill',function(){
console.log($(this).parent());
$(this).parent().parent().remove();
});
I Got the solution for sum:
var sum = 0;
for(var i = 0; i < skillcount; i++){
sum += parseFloat(document.getElementsByName('skill[' + i + '][weightage]')[0].value);
}
if( sum == NaN || sum != 100){
alert('Sum of All skill weightage must be 100');
return false;
}
I have a table whereby people can add rows.
There is a select input in the table that when changed, changes the values in a second select field via ajax.
The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.
I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?
The HTML form is
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
<td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
<td><select name="asset[0][type]">
<option><?php echo $typeoption ?></option>
</select></td>
<td><select class="manuf_name" name="asset[0][manuf]">
<option><?php echo $manufoption ?></option>
</select></td>
<td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
<td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
<td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
<td><select id="site" name="asset[0][site]">
<option><?php echo $siteoption ?></option>
</select></td>
<td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
<td><select id="new_select" name="asset[0][contact]"></select></td>
<!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
<td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
<td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
<td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
The script I have is
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/,
function(str,p1) {
return '[' + (parseInt(p1,10)+1)+ ']'
})
})
return false;
});
});
$(document).ready(function() {
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last')
if ($last.is(':nth-child(2)')) {
alert('This is the only one')
} else {
$last.remove()
}
});
});
$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
$.ajax ({
type : 'post',
url : 'assetprocess.php',
data: {
get_option : $(this).val()
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
})
});
});
</script>
and the assetprocess.php page is
<?php
if(isset($_POST['get_option'])) {
//Get the Site Contacts
$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));
if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
$contactid = $contactrow['contact_id'];
$contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
$contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}
exit;
}
?>
The code is ugly as sin, but this is only a self-interest project at this stage.
Any assistance would be greatly appreciated.
Cheers,
J.
Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/
A few minor HTML changes:
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<td>
<select name="asset[0][type]">
<option>---</option>
<option>Type Option</option>
</select>
</td>
<td>
<select class="manuf_name" name="asset[0][manuf]">
<option>---</option>
<option>
Manuf Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="Serial #" name="asset[0][serial_num]">
</td>
<td>
<input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
</td>
<td>
<input type="text" placeholder="Name or Description" name="asset[0][description]">
</td>
<td>
<select id="site-0" class="chooseSite" name="asset[0][site]">
<option>---</option>
<option>
Site Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
</td>
<td>
<select id="new-site-0" name="asset[0][contact]">
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
});
var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
newId = lastId + 1;
$("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
$("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
return false;
});
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last');
if ($last.is(':nth-child(2)')) {
alert('This is the only one');
} else {
$last.remove();
}
});
$(".chooseSite").change(function(event) {
console.log($(this).attr("id") + " changed to " + $(this).val());
var target = "new-" + $(this).attr('id');
/*$.ajax({
type: 'post',
url: 'assetprocess.php',
data: {
get_option: $(this).val()
},
success: function(response) {
$("#" + target).html(response);
}
});*/
var response = "<option>New</option>";
$("#" + target).html(response);
});
});
Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/
function cloneRow(n) {
if (n - 1 < 0) return false;
var html = "";
html += "<tr class='removable' data-row=" + n + ">";
html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
html += $("#type-" + (n - 1)).html();
html += "<select></td>";
html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
html += $("#manuf-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
html += $("#site-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
html += "</tr>";
return html;
}
It's more work up front, yet offers a lot more control of each part. And much easier to use later.