I have added add/edit/delete function for my table below. I managed to develop the add_row function in JavaScript. The text inputs seem to work when I click on the Add Row button but not the radio buttons. When I select either Yes/No and click on the Add Row button, the selection does not display at the new row created.
I will really appreciate if I could get some guidance in solving this problem.
function add_row() {
var new_name = document.getElementById("new_name").value;
var new_value = document.getElementById("new_value").value;
var new_yes = document.getElementById("new_yes").value;
var new_no = document.getElementById("new_no").value;
var table = document.getElementById("data_table");
var len = (table.rows.length) - 1;
var table_len = (document.querySelectorAll('.data_row').length) + 1;
var row = table.insertRow(len).outerHTML = '<tr class="data_row" id="row' + table_len + '">' +
'<td id="name_row' + table_len + '">' + new_name + '</td>' +
'<td id="qty' + table_len + '">' + new_value + '</td>' +
'<td><input type="radio" id="yes"' + table_len + '"checked></td>' +
'<td><input type="radio" id="no"' + table_len + '"></td>' +
'<td><input type="button" id="edit_button' + table_len + '" value="Edit" class="edit" onclick="edit_row(' + table_len + ')"> <input type="button" value="Delete" class="delete" onclick="delete_row(' + table_len + ')"></td>' +
"</tr>";
document.getElementById("new_name").value = "";
document.getElementById("new_value").value = "";
document.getElementById("new_yes").value = "";
document.getElementById("new_no").value = "";
}
<table style="width:80% table-layout:fixed" align="center">
<table class="table1" style="width:70%" align="center" id="data_table" cellspacing=2 cellspacing=5>
<tr>
<td></td>
<td class="cent"><b>Value</b></td>
<td class="cent"><b>Yes</b></td>
<td class="cent"><b>No</b></td>
<td></td>
</tr>
<tr class="data_row" id="row1">
<label id="group1"> <!--label is used to control the respective group of radio buttons-->
<td id="name_row1">Initial</td>
<!--The input box in the 'Value' column is set as below-->
<td class="cent"><input type="number" value="<%=initial%>" align="center" name="Initial" id="qty1" maxlength="4" size="4"/></td>
<!--The check boxes of 'Yes' and 'No' is created as below-->
<td class="cent"><input type="radio" name="group1" value="Yes" id="yes('1')"></td>
<td class="cent"><input type="radio" name="group1" value="No" id="no('1')"></td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</label>
</tr>
<tr class="data_row" id="row2">
<label id="group2">
<td id="name_row2">Drop Test</td>
<td class="cent"><input type="number" value="<%=droptest%>" align="center" name="Drop Test" id="qty2" maxlength="4" size="4"/></td>
<td class="cent"><input type="radio" name="group2" value="Yes" id="yes('2')"></td>
<td class="cent"><input type="radio" name="group2" value="No" id="no('2')"></td>
<td>
<input type="button" id="edit_button2" value="Edit" class="edit" onclick="edit_row('2')">
<input type="button" value="Delete" class="delete" onclick="delete_row('2')">
</td>
</label>
</tr>
<tr class="data_row" id="row3">
<label id="group3">
<td id="name_row3">Power Up</td>
<td class="cent"><input type="number" value="<%=powerup%>" align="center" name="Power Up" id="qty3" maxlength="4" size="4"/></td>
<td class="cent"><input type="radio" name="group3" value="Yes" id="yes('3')"></td>
<td class="cent"><input type="radio" name="group3" value="No" id="no('3')"></td>
<td>
<input type="button" id="edit_button3" value="Edit" class="edit" onclick="edit_row('3')">
<input type="button" value="Delete" class="delete" onclick="delete_row('3')">
</td>
</label>
</tr>
<tr>
<td><input type="text" id="new_name"></td>
<td class="cent"><input type="text" id="new_value"></td>
<td class="cent"><input type="radio" name="group28" id="new_yes"></td>
<td class="cent"><input type="radio" name="group28" id="new_no"></td>
<td class="cent"><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>
</table>
Sorry if you didn't want me to, but I've rewritten your code on my purpose, since it's quite messy and there were some inappropriate ways of coding.
var divButtons = document.querySelector('.buttons');
var divBoard = document.querySelector('.board');
var inputFir = divButtons.children[0];
var inputSec = divButtons.children[1];
var radioYes = divButtons.children[2];
var radioNo = divButtons.children[3];
var submit = divButtons.children[4];
var radioCount = 1;
submit.addEventListener('click', function(e){
e.stopPropagation();
var div = document.createElement('div');
var input1 = document.createElement('input');
var input2 = document.createElement('input');
var radio1 = document.createElement('input');
var radio2 = document.createElement('input');
radio1.type = 'radio';
radio2.type = 'radio';
radio1.name = radioCount;
radio2.name = radioCount;
radioCount++;
input1.value = inputFir.value;
input2.value = inputSec.value;
if(!radioYes.checked && !radioNo.checked){
radio1.checked = true;
}else if(radioYes.checked){
radio1.checked = true;
}else if(radioNo.checked){
radio2.checked = true;
}
div.append(input1, input2, radio1, radio2);
divBoard.append(div);
});
<div class="board">
</div>
<div class="buttons">
<input type="text" id="input1"/>
<input type="text" id="input2"/>
<input type="radio" name="radio0" id="radioY"/>
<input type="radio" name="radio0" id="radioN"/>
<input type="button" id="submit" value="Add Row"/>
</div>
First of all, you better not to approach the DOM element too much, retrieving any DOM elements costs you 'time'. So, the best way to optimize it is to access the DOM just once or as least as you can and save its address to your variable. Even though you might think you should search for the child elements, like
divButtons.children[0]
however, this is lot faster.
Second, creating DOM using innerHTML is not always the best choice. You can also use createElement method, like I did. If you're interested and wondering why, check this link out.
enter link description here
And also, if you use innerHTML, that means you will risk of sql injection attack. Check this out too.
enter link description here
Thrid, you can stop bubbling event by putting e.stopPropagation(), when the listener event has been fired. To know more about what it is, click here.
enter link description here
Related
I have a function where my input type="number" data-id="weight" checks whether the user typed a divisible by 5 or not. It is perfectly working on my current row but when i add a new row/s, it is not working. Is there anything i missed? I provided my snippet below. Thank you everyone.
To try it. Please type on the weight column a number that is not divisible by 5, then you'll see the error. Add row and do the same, you will not see the error. My target is my function to work with added rows too.
$("#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 + '" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight' + rowIndex + '" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand' + 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);
});
// divisible by only 5
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', () => {
if (input.value % 5 !== 0) {
alert('not valid');
input.value = 5;
}
});
});
<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>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</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="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
This is caused by the event handler for the change event not being fired for dynamically created objects.
When you create an the event handlers like this:
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', () => {
...
}
});
The handler is only mapped for elements that exist when you first run the code. That means any subsequently created dynamic elements will not cause the event to fire.
Instead, use the following syntax to create the event which will catch dynamically created elements by using their selector (input[data-id="weight"]):
$(document).on('change', 'input[data-id="weight"]', function(e) {
if ($(this).val() % 5 !== 0) {
alert('not valid');
$(this).val(5);
}
});
I've removed the other code you had previously that tried to bind the event handler. You don't need to do it that way with jQuery.
Seen here in a working version of your snippet:
$("#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+'" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight'+rowIndex+'" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand'+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);
});
// divisible by only 5
$(document).on('change', 'input[data-id="weight"]', function(e) {
if ($(this).val() % 5 !== 0) {
alert('not valid');
$(this).val(5);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</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="hehe form-control" placeholder="" required id="auto"/>
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove" >
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
Add change event listener after adding the table row. Modified the above code as below:
$("#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+'" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight'+rowIndex+'" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand'+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);
const list = document.querySelectorAll('input[data-id="weight"]');
const input = list[list.length - 1];
console.log(input)
input.addEventListener('change', inputValidation);
});
const inputValidation = (e) => {
if (e.target.value % 5 !== 0) {
alert('not valid');
e.target.value = 5;
}
}
// divisible by only 5
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', inputValidation);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</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="hehe form-control" placeholder="" required id="auto"/>
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove" >
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
I have a simple form that accepts input from a popup form (the user clicks Contour): https://codepen.io/alabamarob/pen/JjGYVjr. The user selects how they would like their input number distributed across dates from a graphic representing skew.
What I'd like to do is populate the "Adjustments" text fields based on the selected distribution curve and ETC amount. For instance, if the user selects the first curve, whatever amount in the ETC amount field would be distributed 10% 25% 65% and populate the adjustments fields accordingly. Likewise, the normal distribution would populate the 20% 60% 20% amounts.
Any pointers would be helpful. Thanks!
//this is the main page
<table><tr><td>
Contour
</td>
<td> <input name="0" type="text" />
</td>
<td> <input name="1" type="text" />
</td>
<td> <input name="2" type="text" />
</td>
</tr>
</table>
<br/>
//this is the popup page
<table>
<tr><td>Choose Countour: <input type="radio" name="skew0" value="neg">
<img src="imgs/0.jpg" width="20px"></td>
<td align="center"><input type="radio" name="skew0" value="pos">
<img src="imgs/1.jpg" width="20px"></td>
<td ><input type="radio" name="skew0" value="no">
<img src="imgs/2.jpg" width="20px"></td>
</tr>
<tr><td>ETC Total Value:</td><td colspan="2" align="right"> <input type="textbox" ></td></tr>
<tr><td colspan="3" align="right"><input type="submit" value="submit" onclick="self.close()"></td></tr></table>```
<script type="text/javascript">
function copy()
{
if(document.getElementById('neg').checked) {
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var n3 = document.getElementById("n3");
var n4 = document.getElementById("n4");
n2.value = n1.value*.4;
n3.value = n1.value*.5;
n4.value = n1.value*.1;
}
if(document.getElementById('pos').checked) {
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var n3 = document.getElementById("n3");
var n4 = document.getElementById("n4");
n2.value = n1.value*.1;
n3.value = n1.value*.7;
n4.value = n1.value*.4;
}
if(document.getElementById('no').checked) {
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var n3 = document.getElementById("n3");
var n4 = document.getElementById("n4");
n2.value = n1.value*.15;
n3.value = n1.value*.7;
n4.value = n1.value*.15;
}
}
</script>
<table border="0" style="background-color: #ffffff; filter: alpha(opacity=40); opacity: 0.95;border:1px black solid;">
<tr>
<td>Enter ETC and Choose Contour: </td>
<td><input type="text" name="n1" id="n1"></td>
<td><input type="radio" name="skew0" id="pos"><img src="imgs/0.jpg" width="20px"></td>
<td align="center"><input type="radio" name="skew0" id="no"><img src="imgs/1.jpg" width="20px"></td>
<td ><input type="radio" name="skew0" id="neg">
<img src="imgs/2.jpg" width="20px"></td>
<td><input type="button" value="Go!" onClick="copy();" /></td>
</tr>
</table>
<br/>
<table border="0"><tr>
<td> </td>
<td>8/21/20</td>
<td>9/25/20</td>
<td>10/30/20</td>
<td></td>
</tr>
<tr> <td>Adjustments:</td><td><input type="text" name="n2" id="n2"/></td><td><input type="text" name="n3" id="n3"/></td><td><input type="text" name="n4" id="n4"/></td><td></td></tr>
</table>
I have an html table with one or more row. I have 4 columns in my table in that one is a checkbox. Two buttons are there "AddRowAbove" and "AddRowBelow". When a particular checkbox is checked and click a button a new row should be added based on the button name. My code looks like this not sure how to achieve the result.
function addNewRowAbove() {
alert("actioned !!!");
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) - 1;
alert(rowNumber + " - " + rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
$('#maintable tbody').append(newRow);
}
function addNewRowBelow() {
alert("actioned !!!");
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1;
alert(rowNumber + " - " + rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
$('#maintable tbody').append(newRow);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr>
<td><input type="checkbox" name="radio" id="radio"></input><input type="hidden" id="rowIndex" value="1" /></td>
<td><input type="text" name="empid"></input>
</td>
<td><input type="text" name="empfname"></input>
</td>
<td><input type="text" name="emplname"></input>
</td>
</tr>
<tr>
<td><input type="checkbox" name="radio1" id="radio1"></input><input type="hidden" id="rowIndex" value="2" /></td>
<td><input type="text" name="empid1"></input>
</td>
<td><input type="text" name="empfname1"></input>
</td>
<td><input type="text" name="emplname1"></input>
</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()"></td>
<td> <input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()"></td>
<td></td>
</tr>
</table>
</form>
I added var selectedRow = $( "input:checked" ).parent().parent(); to both of your functions to find the parent row of the checked element, and then used either $(newRow).insertBefore(selectedRow); or $(newRow).insertAfter(selectedRow); depending on the button clicked.
Hopefully this helps.
UPDATE:
In response to comments requesting that the id's of the rows are kept in order even after adding rows dynamically, I've added a SortRowIDs() function which is called at the end of both addNewRowAbove() and addNewRowBelow().
This function grabs all of the <input type="checkbox"/> tags in the <table id="maintable"></table> and then iterates through them using jQuery's .each() method. Each checkbox's parent row is then assigned an Id based on its order in the table. I also added a few comments in the code so that it is easier to follow.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function SortRowIDs() {
// The code below finds all the <tr> elements in the table WITH checkboxes in them.
// This way, we skip the first row containing column headers and the last row containing buttons
// We use the jQuery .each() method to iterate through jQuery-object arrays
$('#maintable').find('tr > td > input[type="checkbox"]').each(function(index) {
// We assign the parent row of the current checkbox to the variable 'currentRow'
let currentRow = $(this).parent().parent();
// Here we give the current row an id based on its position in the table
$(currentRow).attr('id', 'id_' + (index + 1));
// Prints the id's of each row
console.log('Current row\'s id: ' + $(currentRow).attr('id'));
});
// This prints the id attribute of the selected checkbox's parent row, to show that
// the Id's were successfully assigned by the SortRowIDs() function
console.log('');
console.log('Selected row\'s id: ' + $( "input:checked" ).parent().parent().attr('id'));
}
function addNewRowAbove() {
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) - 1;
var newRow = $('<tr/>');
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '" /><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"/></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
var selectedRow = $( "input:checked" ).parent().parent();
$(newRow).insertBefore(selectedRow);
SortRowIDs();
}
function addNewRowBelow() {
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1;
var newRow = $('<tr/>');
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
var selectedRow = $( "input:checked" ).parent().parent();
$(newRow).insertAfter(selectedRow);
SortRowIDs();
}
</script>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr>
<td>
<input type="checkbox" name="radio" id="radio"/>
<input type="hidden" id="rowIndex" value="1" />
</td>
<td>
<input type="text" name="empid" />
</td>
<td>
<input type="text" name="empfname" />
</td>
<td>
<input type="text" name="emplname" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="radio1" id="radio1" />
<input type="hidden" id="rowIndex" value="2" />
</td>
<td>
<input type="text" name="empid1" />
</td>
<td>
<input type="text" name="empfname1" />
</td>
<td>
<input type="text" name="emplname1" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()">
</td>
<td>
<input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()">
</td>
<td></td>
</tr>
</table>
</form>
You can use insertBefore to append new row above buttons (give id="button" to row content buttons). Try with below solution:
function addNewRowAbove(){
alert("actioned !!!");
var rowNumber=document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber)- 1 ;
alert(rowNumber+" - "+rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio'+rowNumberNew+'"></input><input type="hidden" id="rowIndex'+rowNumberNew+'" value="'+rowNumberNew+'"/></td><td><input type="text" name="empid" id="empid'+rowNumberNew+'"></input></td><td><input type="text" name="empfname" id="empfname'+rowNumberNew+'"></input></td><td><input type="text" name="emplname" id="emplname'+rowNumberNew+'"></input></td>');
newRow.insertBefore('#button');
}
function addNewRowBelow(){
alert("actioned !!!");
var rowNumber=document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1 ;
alert(rowNumber+" - "+rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio'+rowNumberNew+'"></input><input type="hidden" id="rowIndex'+rowNumberNew+'" value="'+rowNumberNew+'"/></td><td><input type="text" name="empid" id="empid'+rowNumberNew+'"></input></td><td><input type="text" name="empfname" id="empfname'+rowNumberNew+'"></input></td><td><input type="text" name="emplname" id="emplname'+rowNumberNew+'"></input></td>');
$('#maintable tbody').append(newRow);
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr><td><input type="checkbox" name="radio" id="radio"></input><input type="hidden" id="rowIndex" value="1"/></td>
<td><input type="text" name="empid"></input></td>
<td><input type="text" name="empfname"></input></td>
<td><input type="text" name="emplname"></input></td>
</tr>
<tr><td><input type="checkbox" name="radio1" id="radio1"></input><input type="hidden" id="rowIndex" value="2"/></td>
<td><input type="text" name="empid1"></input></td>
<td><input type="text" name="empfname1"></input></td>
<td><input type="text" name="emplname1"></input></td>
</tr>
<tr id="button"><td></td><td> <input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()"></td><td> <input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()"></td><td></td></tr>
</table>
</form>
</body>
</html>
I am trying to create new rows when a checkbox is clicked. I have tried using .after() and .insertAfter() to no avail.
Can someone please point me in the right direction?
http://jsfiddle.net/uf0jhd9w/c
HTML:
<tr class="itemSize">
<td>
<span class="danger">*</span><label for="itemSize">Product Sizes:</label>
</td>
<td>
<label for="extra_small">XS</label><input type="checkbox" name="extra_small" id="extra_small" value="XS">
<label for="small">S</label><input type="checkbox" name="small" id="small" value="S">
<label for="medium">M</label><input type="checkbox" name="medium" id="medium" value="M">
<label for="large">L</label><input type="checkbox" name="large" id="large" value="L">
</td>
</tr>
jQuery:
$('#extra_small,#small,#medium, #large, #extra_large').on('change',function(){
var $sizeTr = $('.itemSize');
if(this.checked){
console.log("checked");
var size = $(this).attr("id");
var html =
'<tr class="'+size+'_quantity">'+
'<td>'+
'<span class="danger">*</span><label for="itemQuantity">'+size+' Stock Quantity:</label>'+
'</td>'+
'<td>'+
'<input type="number" min="1" name="itemQuantity" placeholder="Enter Product Quantity" value=""/>'+
'</td>'+
'</tr>';
//$('.itemSize').after(html);
$(html).insertAfter($sizeTr);
//console.log( $(html));
}else{
$('tr.'+size+'_quantity').hide();
}
});
Got your answer.
Please refer this Fiddle: http://jsfiddle.net/mayurRahul/frpnsnpv/
HTML:
<tr class="itemSize">
<td>
<span class="danger">*</span><label class="itemSize">Product Sizes:</label>
</td>
<td>
<label for="extra_small">XS</label><input type="checkbox" name="extra_small" id="extra_small" value="XS">
<label for="small">S</label><input type="checkbox" name="small" id="small" value="S">
<label for="medium">M</label><input type="checkbox" name="medium" id="medium" value="M">
<label for="large">L</label><input type="checkbox" name="large" id="large" value="L">
</td>
</tr>
JavaScript:
$('#extra_small,#small,#medium, #large, #extra_large').on('change',function(){
var $sizeTr = $('.itemSize');
if(this.checked){
console.log("checked");
var size = $(this).attr("id");
var html =
'<tr class="'+size+'_quantity">'+
'<td>'+
'<span class="danger">*</span><label for="itemQuantity">'+size+' Stock Quantity:</label>'+
'</td>'+
'<td>'+
'<input type="number" min="1" name="itemQuantity" placeholder="Enter Product Quantity" value=""/>'+
'</td>'+
'</tr>';
//$('.itemSize').after(html);
$(html).insertAfter($sizeTr);
//console.log( $(html));
}else{
$('tr.'+size+'_quantity').hide();
}
});
Make sure you select the good element when you add your row (see answers from this link). Add an ID to your table.
<table id="myTable">
<thead>
<!-- Table headers -->
</thead>
<tbody>
<!-- Table contents -->
</tbody>
</table>
$('#myTable > tbody:last').append('<tr>...</tr><tr>...</tr>');
To add row after last 'tr'
$("#table tr:last").after("<tr><td>cell</td></tr>");
I have a simple table with a series of Yes/No radio button questions and have added some Javascript that should apply a red colour to the label of an adjacent text area input. It's working but not for the first row in the table - all other rows it works.
Here's a cutdown version of the html for the first 3 rows in the table:
<table width="71%" class="record">
<tr>
<td width="63%" valign="top" class="field_name_left"><p><strong>Section 1</strong><br>
(a) section 1A.</p>
</td>
<td width="11%" valign="top" class="field_data">
<input type="radio" name="Scale1A" value="Yes" validate = "required:true " class = "radioClick">Yes
<input type="radio" name="Scale1A" value="No" validate = "required:true " class = "radioClick">No <label for = "Scale1A" class = "error">Please ensure this is completed</label> </td>
<td width="26%" valign="top" class="field_data">
<span class="field_name_left style1" id = "Scale1AWhereLabel"><strong>Where:</strong></span>
<textarea id = "Scale1AWhere" class="where" name="Scale1AWhere" cols="25" rows="2" validate="required:'input[name=Scale1A][value=Yes]:checked'"> </textarea>
<label for = "Scale1AWhere" class = "error">Please ensure this is completed</label> </td>
</tr>
<tr>
<td valign="top" class="field_name_left"> (b) section 1B.</td>
<td valign="top" class="field_data"> <input type="radio" name="Scale1B" value="Yes" validate = "required:true " class = "radioClick" />
Yes <input type="radio" name="Scale1B" value="No" validate = "required:true " class = "radioClick" />
No <label for = "Scale1B" class = "error">Please ensure this is completed</label> </td>
<td valign="top" class="field_data"><span class="field_name_left style1" id = "Scale1BWhereLabel"><strong>Where:</strong></span>
<textarea id = "Scale1BWhere" class="where" name="Scale1BWhere" cols="25" rows="2" validate="required:'input[name=Scale1B][value=Yes]:checked'"></textarea> <label for = "Scale1BWhere" class = "error">Please ensure this is completed</label> </td>
</tr>
<tr>
<td width="63%" valign="top" class="field_name_left"><strong>Section 2.</td>
<td valign="top" class="field_data">
<input type="radio" name="Scale2" value="Yes"validate = "required:true" class="radioClick">Yes <input type="radio" name="Scale2" value="No"validate = "required:true" class="radioClick">No <label for = "Scale2" class = "error">Please ensure this is completed</label> </td>
<td valign="top" class="field_data">
<span class="field_name_left style1" id = "Scale2WhereLabel"><strong>Where:</strong></span>
<textarea id = "Scale2Where" class="where" name="Scale2Where" cols="25" rows="2" validate="required:'input[name=Scale2][value=Yes]:checked'"></textarea> <label for = "Scale2Where" class = "error">Please ensure this is completed</label></td>
</tr>
<tr class="submit_btn">
<td colspan="3">
<input type="submit" name="-edit" value="Finish">
<input type="reset" name="reset" value="Reset"> </td>
</tr>
</table>
and here's my script:
$(".radioClick").click(function(){
theStr = $("#"+this.name+"Where").val().length;
if($(this).val()=="Yes" && theStr == 0){
$("#"+this.name+"WhereLabel").addClass("emphasise");
} else {
$("#"+this.name+"WhereLabel").removeClass("emphasise");
}
$(".where").keyup(function(){
str = this.value.length;
if(str == 0){
$("#"+this.name + "Label").addClass("emphasise");
}else{
$("#"+this.name + "Label").removeClass("emphasise");
}
});
});
$.metadata.setType("attr", "validate");
$("#editRecord").validate();
You can see this in action over at this jsFiddle
For some reason that I can't fathom the Where label for the Question 1A is never changed to red when the Yes button is clicked, but is for all others?
Issue is an extra space in your text area. You need to trim it. or remove it.
theStr = $.trim($("#"+this.name+"Where").val()).length;
Extra space in the text area:-
<textarea id = "Scale1AWhere" class="where"
name="Scale1AWhere" cols="25" rows="2"
validate="required:'input[name=Scale1A][value=Yes]:checked'"> </textarea>
Fixed Code