How to add new table row? - javascript

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>");

Related

HTML, JavaScript - Radio Button Selection Doesn't Display In New Row

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

How to calculate total sum of checkbox values depend on quantity in textbox

I have the following table
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" value="1"></td>
<td>$550</td>
</tr>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
Table example
I found how to calculate the sum of checkboxes values:
<script>
$(document).ready(function () {
var $inputs = $('input[type="checkbox"]')
$inputs.on('change', function () {
var sum = 0;
$inputs.each(function() {
if(this.checked)
sum += parseInt(this.value);
});
$("#price").val(sum);
});
});
</script>
The question is:
If user will update the quantity in textbox, i need to update the total.
I want it to work in two ways: quantity changed before or after checkbox has been checked.
So the value in "Cost" column is equal to checkbox value. I do not want to modify "Cost" column. I need total to be shown at the bottom of the table in "textbox with id="price" textbox.
Case:
User checked the first checkbox #price should be updated with 450.
User checked the second checkbox #price should benow 1000.
User changed the quantity to 2 in the row with the first checkbox.Now #price should be updated to 1450
Thanks in advance!
To achieve this you should loop through the table body's row for that use the code as
$('table tbody tr').each(function()
{
//do something
});
and then find the checkbox in that row. You can check if the check box is checked by using $tr.find('input[type="checkbox"]').is(':checked') this code. It will find a check box in the row and it will check whether it is checked or not.
var $columns = $tr.find('td').next('td').next('td'); This code is used to retrieve the column Quantity.
We call the function calculateSum() to calculate the sum coast of checked rows in both textbox change event and checkbox change event.
$(document).ready(function() {
function calculateSum(){
var sumTotal=0;
$('table tbody tr').each(function() {
var $tr = $(this);
if ($tr.find('input[type="checkbox"]').is(':checked')) {
var $columns = $tr.find('td').next('td').next('td');
var $Qnty=parseInt($tr.find('input[type="text"]').val());
var $Cost=parseInt($columns.next('td').html().split('$')[1]);
sumTotal+=$Qnty*$Cost;
}
});
$("#price").val(sumTotal);
}
$('#sum').on('click', function() {
calculateSum();
});
$("input[type='text']").keyup(function() {
calculateSum();
});
$("input[type='checkbox']").change(function() {
calculateSum();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sum" type="button">Calculate</button><br/>
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" name="chck" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" class="chck" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$550</td>
</tr>
</table>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
<div class="serve" id="service">
<form action="" id="roomform" onsubmit="return false">
<div class="order">
<fieldset>
<legend>Tell us where to clean:</legend>
<p>
<input value="30" type="checkbox" id="myCheck" class="sum" name="myCheck" oninput="x.value=parseInt(bedroom.value)*30.00"/>
<label for="sleeping" class="contain">Bedrooms (P30/room) </label>
<input type="number" id="a" class="room" value="1" min="1" max="20" onchange="calculateTotal()"/>
Total: P <span id="costPrice"> </span
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" name="myCheck1" onclick="calculateTotal()" />
<label for="sitting" class="contain">Sitting room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Dining room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
Extra services:</p>
<p>
<input value="15" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Carpet Cleaning (P 15/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="3" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Window Cleaning (P 3/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<div class="grandPrice" >
Grand Total Price: P<span id="grandTotal">0</span>
</div>
</fieldset>
</div>
</form>
<script>
// When a checkbox is clicked
/*$('#order input[type=checkbox]').click(function() {
// Get user input and set initial variable for the total
inputBox = parseInt($('#a').val());
bedroomPrices = 0;
// If it's checked, add the current value to total
if($(this).prop('checked'))
{
thisValue = parseInt($(this).val());
bedroomPrices = bedroomPrices + thisValue;
}
// Output the total checkbox value multipled against user input
$('#costPrice').html(bedroomPrices * inputBox);
});*/
var checkbox = document.getElementsByClassName('sum'),
inputBox = document.getElementById('a'),
GrandTotal = document.getElementById('grandTotal');
//"(this.checked ? 1 : -1);" this sees if checkbox is checked or unchecked by adding or subtracting it (1 :-1)
//make sure that each checkbox total is added if its checked
for (var i=0; i < checkbox.length; i++) {
checkbox[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
grandTotal.innerHTML = parseFloat(grandTotal.innerHTML) + add
}
}
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="indent_list">
<table border="1">
<thead>
<tr>
<th>rate</th>
<th>quantity</th>
<th>coltotal</th>
</tr>
</thead>
<body>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="1"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
</body>
<tfoot>
<tr>
<th class="rateRow"></th>
<th class="quantityRow"></th>
</tr>
<tr>
<th colspan="2" class="totalRow"></th>
</tr>
</tfoot>
</table>
</div>
> button
<input type="checkbox" class="btn btn-info checkbox" onclick="calculateCheck()">
<input type="button" class="btn btn-info" onclick="calculate()" value="Calculate">
> script
<script>
function calculateCheck() {
var check = $('.checkbox').prop('checked');
if (check) {
calculate()
} else {
$('.rateRow').text('');
$('.quantityRow').text('');
$('.totalRow').text('');
}
}
function calculate() {
var rateRow = '';
var quantityRow = '';
var totalRow = '';
var rate = 0;
var quantity = 0;
var total = 0;
// alert(quantitycol);
$('tbody tr').each(function () {
var ratecol = $('td .rate', this).val();
var quantitycol = $('td .quantity', this).val();
var coltotal = ratecol * quantitycol;
$('td .coltolal', this).val(coltotal);
// alert(a);
rate += +$('td .rate', this).val();
quantity += +$('td .quantity', this).val();
total = rate * quantity;
});
rateRow += rate;
quantityRow += quantity;
totalRow = total;
$('.rateRow').text(rateRow);
$('.quantityRow').text(quantityRow);
$('.totalRow').text(totalRow);
}
</script>

creating new row on button click

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>

disable input fields on radio button change

I have four radio buttons (fixed,percentage,monthly,yearly), I created A div with five fields, start price, end price, start date, end date and amount. What I want is when clicked on fixed or percentage button all five fields should be enabled and when clicked on monthly or yearly button start price and end price fields should be disabled (as I don't want to pass the values of these fields). I also have a add more mutton need to do the same for it i.e when add more rows to fixed/percentage all fields should be enabled and while adding rows to monthly/yerly fields, start/end price fields should be disabled. Thanks in advance.
HTML code for labels
<label class="col-sm-2 control-label" for="radioo">Commission type <b style="color:red;">*</b></label>
<div class="col-lg-10" required>
<label class="custom-control custom-control-primary custom-radio">
<input class="custom-control-input" type="radio" name="comission_type" value="0" checked="checked">
<span class="custom-control-indicator"></span>
<span class="custom-control-label">Fixed price</span>
</label>
<label class="custom-control custom-control-primary custom-radio">
<input class="custom-control-input" type="radio" name="comission_type" value="1">
<span class="custom-control-indicator"></span>
<span class="custom-control-label">Percentage wise</span>
</label>
<label class="custom-control custom-control-primary custom-radio">
<input class="custom-control-input" type="radio" name="comission_type" value="2">
<span class="custom-control-indicator"></span>
<span class="custom-control-label">Monthly</span>
</label>
<label class="custom-control custom-control-primary custom-radio">
<input class="custom-control-input" type="radio" name="comission_type" value="3">
<span class="custom-control-indicator"></span>
<span class="custom-control-label">Yearly</span>
</label>
</div>
HTML code for div
<div id="fixPerDiv" style="display:block;">
<div class="form-group">
<div class="col-lg-11 col-lg-offset-1">
<div class="table-responsive">
<table class="table" id = 'commision_tbl' >
<tr>
<td width = '20%'>Start price</td>
<td width = '20%'>End price</td>
<td width = '20%'>Start date</td>
<td width = '20%'>End date</td>
<td width = '20%'>Comission</td>
<td> </td>
</tr>
<tr>
<td><input type="number" name="commissions_start_price[]" class="form-control" value="" placeholder="Start Price" required="required" /></td>
<td><input type="number" name="commissions_end_price[]" class="form-control" value="" placeholder="End Price" required="required"/></td>
<td><div class="input-with-icon"><input type="text" data-provide="datepicker" value="" data-date-today-highlight="true" name="start_date[]" class="form-control" placeholder="Start date" required="required"/><span class="icon icon-calendar input-icon"></span></div></td>
<td><div class="input-with-icon"><input type="text" data-provide="datepicker" value="" data-date-today-highlight="true" name="end_date[]" class="form-control" placeholder="End date" required="required"/><span class="icon icon-calendar input-icon"></span></div></td>
<td><input type="number" name="commissions_amount[]" class="form-control" value="" placeholder="Commision price" required="required"/></td>
<td> </td>
</tr>
<tr>
<td colspan="6" align = "center">
<input type="button" value="Add More" id="price_addmorebtn" class="btn btn-outline-info">
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
Script code for disabling two fields for monthly/yearly radio buttons (Incomplete)
<script>
$(document).ready(function() {
console.log('called');
$('input[type=radio][name=comission_type]').change(function() {
if (this.value == '0' || this.value == '1') {
$("#fixPerDiv").css("display","block");
}
else if (this.value == '2' || this.value == '3') {
$("#fixPerDiv").css("display","block");
}
});
});
</script>
Script for add button
<script>
$('#price_addmorebtn').click(function(){
var tr = "<tr>";
tr += "<td><input type=\"number\" name=\"commissions_start_price[]\" class=\"form-control\" placeholder=\"Start Price\" required /></td>";
tr += "<td><input type=\"number\" name=\"commissions_end_price[]\" class=\"form-control\" placeholder=\"End Price\" required /></td>";
tr += "<td><div class=\"input-with-icon\"><input name=\"start_date[]\" placeholder=\"Start date\" data-provide=\"datepicker\" data-date-today-highlight=\"true\" class=\"form-control\" required /><span class=\"icon icon-calendar input-icon\"></span></div></td>";
tr += "<td><div class=\"input-with-icon\"><input name=\"end_date[]\" placeholder=\"Start date\" data-provide=\"datepicker\" data-date-today-highlight=\"true\" class=\"form-control\" required /><span class=\"icon icon-calendar input-icon\"></span></div></td>";
tr += "<td><input type=\"number\" name=\"commissions_amount[]\" class=\"form-control\" placeholder=\"Commision price\" required /></td>";
tr += "<td><span class = 'romoverow icon icon-close' style=\"cursor:pointer; padding-top:12px;\" title=\"Click to remove this row.\"></span></td>";
$('#commision_tbl tr:last').before(tr);
});
$(document).on('click','.romoverow',function(){
//alert('Hello');
$(this).closest( 'tr').remove();
});
Try this:
HTML code for div
<div id="fixPerDiv" style="display:block;">
<div class="form-group">
<div class="col-lg-11 col-lg-offset-1">
<div class="table-responsive">
<table class="table" id = 'commision_tbl' >
<tr>
<td width = '20%'>Start price</td>
<td width = '20%'>End price</td>
<td width = '20%'>Start date</td>
<td width = '20%'>End date</td>
<td width = '20%'>Comission</td>
<td> </td>
</tr>
<tr>
<td><input type="number" name="commissions_start_price[]" class="form-control" value="" placeholder="Start Price" required="required" /></td>
<td><input type="number" name="commissions_end_price[]" class="form-control" value="" placeholder="End Price" required="required"/></td>
<td><div class="input-with-icon"><input type="text" data-provide="datepicker" value="" data-date-today-highlight="true" name="start_date[]" class="form-control start_date" placeholder="Start date" required="required"/><span class="icon icon-calendar input-icon"></span></div></td>
<td><div class="input-with-icon"><input type="text" data-provide="datepicker" value="" data-date-today-highlight="true" name="end_date[]" class="form-control end_date" placeholder="End date" required="required"/><span class="icon icon-calendar input-icon"></span></div></td>
<td><input type="number" name="commissions_amount[]" class="form-control" value="" placeholder="Commision price" required="required"/></td>
<td> </td>
</tr>
<tr>
<td colspan="6" align = "center">
<input type="button" value="Add More" id="price_addmorebtn" class="btn btn-outline-info">
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
Script for add button
$('#price_addmorebtn').click(function(){
var selected_val = $("input[type=radio][name=comission_type]:checked").val();
var date_disabled="";
if (selected_val == '2' || selected_val == '3') {
date_disabled=" disabled ";
}
var tr = "<tr>";
tr += "<td><input type=\"number\" name=\"commissions_start_price[]\" class=\"form-control\" placeholder=\"Start Price\" required /></td>";
tr += "<td><input type=\"number\" name=\"commissions_end_price[]\" class=\"form-control\" placeholder=\"End Price\" required /></td>";
tr += "<td><div class=\"input-with-icon\"><input name=\"start_date[]\" placeholder=\"Start date\" data-provide=\"datepicker\" data-date-today-highlight=\"true\" class=\"form-control start_date\" required"+date_disabled+" /><span class=\"icon icon-calendar input-icon\"></span></div></td>";
tr += "<td><div class=\"input-with-icon\"><input name=\"end_date[]\" placeholder=\"Start date\" data-provide=\"datepicker\" data-date-today-highlight=\"true\" class=\"form-control end_date\" required"+date_disabled+" /><span class=\"icon icon-calendar input-icon\"></span></div></td>";
tr += "<td><input type=\"number\" name=\"commissions_amount[]\" class=\"form-control\" placeholder=\"Commision price\" required /></td>";
tr += "<td><span class = 'romoverow icon icon-close' style=\"cursor:pointer; padding-top:12px;\" title=\"Click to remove this row.\"></span></td>";
$('#commision_tbl tr:last').before(tr);
});
$(document).on('click','.romoverow',function(){
//alert('Hello');
$(this).closest( 'tr').remove();
});
Script code for disabling two fields for monthly/yearly radio buttons
$('input[type=radio][name=comission_type]').change(function() {
if (this.value == '0' || this.value == '1') {
$(".start_date").attr("disabled",false);
$(".end_date").attr("disabled",false);
}
else if (this.value == '2' || this.value == '3') {
$(".start_date").attr("disabled",true);
$(".end_date").attr("disabled",true);
}
});

add select box with row using JavaScript

I want that in newly created all options of select box to be present and I want to do it javascript. But I cant figure out how to do when there are too many options
<table id="newtable">
<tr>
<td>
<input name="name" type="text" id="name"/>
</td>
<td>
<select name="gender" id="gender">
<option>Male</option>
<option>Female</option>
</select>
</td>
<td>
<input name="add_button" type="button" id="add_button" value="Add"/>
</td>
<tr>
</table>
var itemCount = 0;
$(document).ready(function() {
var objs = [];
var temp_objs = [];
$("#add_button").click(function() {
var html = "";
var obj = {
"name" : $("#name").val(),
"gender" : $("#gender").val(),
}
$("#name").val('');
$("#gender").val(''),
objs.push(obj);
itemCount++;
html = "<tr>" +
"<td><INPUT type='text' name='txt1[]' value='" + obj['name'] + "'/></td>" +
"<td><select><option>" + obj['gender'] + "</select></option></td></tr>";
$("#newtable").append(html);
});
});
Just make it as simple. Use below Code. It will solve your issue.
<script type="text/javascript">
$(document).ready(function(){
$( "#add_button" ).click(function() {
var newVal=$("#name").val();
var s= document.getElementById('gender');
s.options[s.options.length]= new Option(newVal);
});
});
</script>
And your html will be as below:
<table id="newtable">
<tr>
<td>
<input name="name" type="text" id="name"/>
</td>
<td>
<select name="gender" id="gender">
<option>Male</option>
<option>Female</option>
</select>
</td>
<td>
<input name="add_button" type="button" id="add_button" value="Add"/>
</td>
<tr>
</table>
I believe clone() will be the best option for your example. You can copy the behavior of the button as well by using clone(true, true) (sets the options withDataAndEvents and deepWithDataAndEvents). Run the code below to check:
$(document).ready(function() {
$(".add_button").click(function() {
var currentRow = $(this).parents("tr");
var nr = currentRow.clone(true, true);
nr.find(".name").val('');
currentRow.after(nr); //instead of `$("#newtable").append(nr);`: it places the new row after the clicked row
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="newtable">
<tr>
<td>
<input name="name" type="text" class="name" />
</td>
<td>
<select name="gender" class="gender">
<option>Male</option>
<option>Female</option>
</select>
</td>
<td>
<input name="add_button" type="button" class="add_button" value="Add" />
</td>
</tr>
</table>
From your code, I needed to add a slash in the last <tr> to close it and also change the ids to classes (since there are going to be a lot of them).
Hope it helps!

Categories

Resources