HTML jquery: onclick function to delete dynamic table row is not calling - javascript

I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.
const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td> <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td> <td><input type="text" class="form-control" value="${price}" title="" ></td> <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td> </tr>`;
// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
var template_add = $('#hidden-template').text();
function render(props) {
return function(tok, i) {
return (i % 2) ? props[tok] : tok;
};
}
var items = [ { sno: '1', optionVal: '0', price: '0' } ];
var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);
$('tbody').append(items.map(function(item) {
return dynamic_HTML.map(render(item)).join('');
}));
});
// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('.add-new').on('click', function () {
$("#productTable").each(function () {
var tr_last = $('tbody > tr:last', this).clone();
var td_no = tr_last.find('td:first');
var serialNumber = parseInt(td_no.text()) + 1;
// https://stackoverflow.com/a/6588327/5081877
var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
var tr_first_price = parseFloat(tr_first_input.val()) || 0;
console.dir( tr_first_price );
totalamount += tr_first_price;
$('#totalAdd').text(totalamount);
var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
// option:selected | .find(":selected") ~ .text(), ~.attr('value');
var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
console.log(' Text : ', optionText );
console.log('Value : ', selectedValue );
// https://stackoverflow.com/a/39065147/5081877
$('tbody', this).append([
{ sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
].map(dynamic_JS).join(''));
var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
last_optionSel.val( selectedValue );
tr_first_input.val( 0 );
// https://stackoverflow.com/a/13089959/5081877
var first_optionSel = $('#productOption');
//$('tbody > tr:first > td:nth-child(2) > select ');
first_optionSel.val( 0 );
return;
});
});
var totalamount = 0; // tr#mainRow
$('table#productTable > tbody ').on('keyup', 'input', function(e) {
var total =
$(e.delegateTarget)
.find('input')
.map(function() {
return parseFloat($(this).val()) || 0;
})
.get()
.reduce(function(a, b) {
return a + b;
});
$('#total').text(total);
});
<!-- Remove row - javascript & Jquery -->
$('.remove-row').on('click', function () {
$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove();
});
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>No.</th><th>Product</th><th>Price</th><th>Action</th>
</tr>
</thead>
<tbody id="mainBody">
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>
Expected Total:<span id="total">0</span><br>
Added Total:<span id="totalAdd">0</span>
</td>
<td></td>
</tr>
</tfoot>
</table>
<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>
<script id="hidden-template" type="text/x-custom-template">
<tr id="mainRow">
<td>${sno}</td>
<td>
<select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
<option value="0"> -- Select One --</option>
<option value="1"> IPhone </option>
<option value="2"> MAC </option>
<option value="3"> Windows </option>
</select>
</td>
<td>
<input id="number_only" pattern="[0-9]" type="text" class="form-control" />
</td>
<td><!-- glyphicon-plus | glyphicon-remove -->
<button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
</td>
</tr>
</script>
</body>
Stackoverflow snippet - using javascript onclick function remove current row is working fine.
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
as part of jsfiddle - test and plane html file the code is not working at-least with javascript.
Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}
Iam unable to solve it as new to jquery and its xpath element navigation.

There are two issues with your code:
$('table#productTable:.remove-row').on('click', function () {
here :. is an syntax error, and it is showing in console.
Second to put an event listener on dynamic html, you have to use $(document).on() like:
$(document).on('click', '.remove-row', function(){
Check the updated working fiddle
here

I have added events using on click event handler as elements get added dynamically.
Have updated both events:
1. Event for remove button
$('table#productTable').on('click', '.remove-row', function() {
//$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
//$(element).parent().remove();
//});
});
2. Event for input tag
$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
$.each($('input[type=text]'), function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
});
Refer this fiddle

Please change $('.row).onclick like this
$('table#productTable').on('click', '.remove-row', function()
And remove this $("#productTable").each(function () {

Related

Hide selected option at dynamically form jquery

I need to achieve something like when a user selects an option from one select box the option should be hidden for the other select boxes. When a selected option changes the previously selected option should become available again to the other select boxes. But my code seem like only can work at the static selection box.
var i = 0;
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() {
let value = $(this).val();
$(this).siblings('.s').children('option').attr('disabled', false);
$('.s').each(function() {
$(this).siblings('.s').children('option[value=' + $(this).val() + ']').attr('disabled', 'disabled');
})
});
});
function addRow() {
var tr = '<tr class="cb" id="row_' + i + '"><td>';
tr += '<select class="s form-control select2" id="name1_' + i + ' first" name="name[]" >';
tr += '<option id="1">tan</option><option id="2">lim</option><option id="3">vin</option><option id="4">alex</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function() {
$('.listable .cb').each(function(index, item) {
console.log($('#amt1_' + index).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center"><a href="#" class="btn btn-info addRow">+</th>
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
If you want to dynamically update each select, you will need to do a few things:
Have a dynamic list in a data structure
Be able to figure out what is selected
Update (or recreate) the dropdowns when:
a selection is made or
a row is added or
a row is removed
This way you separate the view from the data backing it.
Update: Instead of re-rendering the options for each select, I toggle their "disabled" state.
let rowId = 0;
const options = [
{ id: 1, name: "tan" },
{ id: 2, name: "lim" },
{ id: 3, name: "vin" },
{ id: 4, name: "alex" },
];
function getSelections() {
return $('select.select2')
.map((i, sel) => $(sel).val()).toArray()
.map(id => parseInt(id, 10));
}
function fixSelections() {
const selections = getSelections();
$('select.select2').each((i, sel) => {
let $sel = $(sel), val = $sel.val();
$sel.find('option').each((j, opt) => {
let $opt = $(opt);
if ($opt.val() !== val && selections.includes(parseInt($opt.val(), 10))) {
$opt.attr('disabled', true);
} else {
$opt.removeAttr('disabled');
}
});
});
}
function populateOptions() {
const selections = getSelections();
return options.map(option => {
return `
<option value="${option.id}"
${selections.includes(option.id) ? 'disabled="disabled"' : ''}>
${option.name}
</option>
`;
});
}
function addRow() {
const tr = `
<tr class="cb" id="row_${rowId}">
<td>
<select class="s form-control select2" id="name1_${rowId}_first" name="name[]">
${populateOptions()}
</select>
</td>
<td>
<input type="number" name="winlose[]" id="amt1_${rowId}" class="form-control">
</td>
<td style="text-align:center">
-
</td>
</tr>
`;
rowId++;
$('tbody').append(tr);
}
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() {
let value = $(this).val();
$(this).siblings('.s')
.children('option')
.attr('disabled', false);
$('.s').each(function() {
$(this).siblings('.s')
.children('option[value=' + $(this).val() + ']')
.attr('disabled', 'disabled');
})
});
fixSelections();
});
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
fixSelections();
});
$('.savebtn').on('click', function() {
$('.listable .cb').each(function(index, item) {
console.log($('#amt1_' + index).val());
});
});
$(document).on('change', 'select.select2', e => fixSelections());
option {
color: #000;
font-style: normal;
font-weight: bold;
}
option[disabled] {
color: #777;
font-style: italic;
font-weight: normal;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>Name</th>
<th>Amount</th>
<th style="text-align:center"><a href="#" class="btn btn-info addRow">+</th>
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
</div>
My solution was to show and enable all everytime something changes then disable and hide all of the options with same value as the ones selected and re-enable and show the one selected in the current select:
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() { //1
$('.s option').prop('disabled',false);//enable all options //n
$('.s option').show();//show all options //n
$('.s option:selected').each(function(index){// disable and hide all of the current selected values from other select boxes //1 to select boxes n
let value = $(this).val();
$('.s option[value='+value+']').prop('disabled',true);//disable all with same value //select boxes n
$('.s option[value='+value+']').hide();//hide them //select boxes n
$(this).prop('disabled',false);//re-enable the current one //1
$(this).show();//and show it //1
$(this).prop('selected',true);//just to be sure re-select the option afterwards //1
});
});
});
I think you can perform this thing with css check snippet
option:checked { display: none; }
option:checked { display: none; }
<select>
<option>A for Alex</option>
<option selected>B for Billy</option>
<option>C for Cody</option>
<option>D for Danny</option>
</select>

How to delete dynamically added row using jQuery?

I am trying to put a 'Delete' button after each of the row of my table.The delete button should function in such a way that it should only get activated when a new row is added. And if out of two rows one row is deleted the delete button of the existing row should also get deactivated.Any help will be appreciated. Thanks.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
/*for enable field*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="16%"></td>
</tr>
</thead>
<tbody>
<tr id="id01" name="row">
<td>
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<option value="GDS">Guides</option>
<option value="LOF">Latest Offers</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" id="Button4" value="Delete Row" disabled="true" class="DeleteButton" name="Button4" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
You can get the count of rows in the table on every 'Add New Row' button and 'Delete Row' button click by:
var Count = $('#dataTable tr').length;
Then using the value of Count you can enable/disable the delete button e.g
if(Count < 2 )
//code to disable
else
//code to enable
I don't know if I get your question right, but I would try to do it like so:
I would handle this over a class namend 'active'. You also can give this class a disabled style. Also I would toggle the show/hide function of jquery if the button was clicked. And if one button is the last man standing - I would hide all. So it cant be clicked anymore. You can also ignore the 'active'-Class if you juste need to show/hide the buttons. The buttons should have a specific class 'del-btn'.
Note: Class 'active' is just for showing the button but disable/enable. Show/hide is for 'removing' the button.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
// If you want to activate ALL buttons:
$('.del-btn').addClass('active');
// If just the added row should be active:
$clone.find('.del-btn').addClass('active');
$(".del-btn").show();
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
if(!$(this).hasClass('active')){
// removing is allowed
$(this).closest("tr").remove();
// Now you can check, if the rest should be shown or not
var btns = $('.del-btn').length; // count the buttons in the dom
if(btns>0){
if(btns == 1){
$(".del-btn").hide();
}else{
$(".del-btn").show();
}
}
}else{
// removing is disallowed
}
});
``````````````````````````for enable field``````````````````````
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});

append line add autocomplete jQuery

I have made an autocomplete on a form where its possible to add new line.
However my autocomplete locks only to the first item.
Can you help me getting the autocomplete to work on appended lines.
jsFiddle: https://jsfiddle.net/r65x9aj0/3/
Javascript:
var globalNewIndex = 0;
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(document).ready(function() {
$('#fixed_name_'+globalNewIndex).autocomplete({
source: availableAttributes
});
$("#add").click(function() {
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
globalNewIndex++;
$('#fixed_name_'+globalNewIndex).autocomplete({
source: availableAttributes
});
$('#mytable tbody>tr:last .emptythis').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
HTML:
<table id="mytable" class="table table-hover">
<thead>
<tr style="font-weight: bold">
<td>Item number
</td>
<td>Price EUR
</td>
</tr>
</thead>
<tbody>
<tr class="person">
<td>
<input type="text" name="fixed_name[0]" id="fixed_name_0" class="form-control emptythis" autocomplete="off" />
</td>
<td>
<input type="number" name="fixed_price[0]" id="fixed_price_0" class="form-control emptythis" autocomplete="off" />
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-md-3">
<button type="button" class="btn btn-success btn-block btn-lg" id="add">Add line
</button>
</div>
<div class="col-md-9">
<button type="submit" class="btn btn-primary btn-block btn-lg" id="searchinternal">Update
</button>
</div>
</div>
</form>
Here is an updated jsfiddle following your code:
Updated fiddle
I initialized Autocomplete dynamically and created a template for the new row because the clone function cloned the instance of autcomplete, which is not good.
Here is your new javascript:
$(document).ready(function() {
$(document).on('keydown.autocomplete', '#mytable tbody>tr:last input', function() {
$(this).autocomplete({
source: availableAttributes
});
});
$("#add").click(function() {
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
var $newRow = $('<tr class="person"><td><input type="text" class="form-control emptythis ui-autocomplete-input" autocomplete="off"></td><td><input type="number" name="fixed_price[1]" id="fixed_price_1" class="form-control emptythis" autocomplete="off"></td></tr>');
$newRow.insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds);
globalNewIndex++;
$('#mytable tbody>tr:last .emptythis').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
// previous code
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
// changed lines of code
var $newRow = $('<tr>' + $('#mytable tbody>tr:first').html() + '</tr>');
$newRow.find('input').attr('name', changeIds ).attr('id', changeIds );
$('#mytable tbody').append($newRow);
The code didn't work because of the clone(true).
I would suggest a 'template' function for the row though.
As for the previous comment, I would not suggest putting it .on('keypress', ... because this gets fired every time you press a key (you can however listen only 'once' with one, but this won't solve your issue, since it won't get fired the 'second' time then).
It is not working because of you are adding the textbox dynamically and for dynamic html the autocomplete is instantiate in different way like:
var selector = '.searchInput';
$(document).on('keydown.autocomplete', selector, function() {
$(this).autocomplete(options);
});

Duplicating table rows with clone

I am having an issue I am struggling to resolve. I have two tables
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table1">
<thead>
<tr>
<th>Campaign Type</th>
<th>Deployment Date</th>
<th>Additional Information</th>
</tr>
</thead>
<tbody>
<tr class='template'>
<td>
<select class="selectType" name='typeInput[0][campType]' id="campInput">
<option value=""></option>
<option value="Main">Main</option>
<option value="Other">Standalone</option>
</select>
</td>
<td>
<input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
<td>
<textarea name='typeInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
</tr>
</tbody>
</table>
<a id='add' class="pull-right btn btn-default">Add Row</a>
<a id='delete' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table4">
<thead>
<tr>
<th>Additional Information</th>
<th>Deployment Date</th>
</tr>
</thead>
<tbody>
<tr class='template4'>
<td>
<textarea name='amendsInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
<td>
<input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
</tr>
</tbody>
</table>
<a id='add4' class="pull-right btn btn-default">Add Row</a>
<a id='delete4' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
One table has 3 inputs, the other has 2. When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem. The second table I end everything with 4 e.g. table4, template4, add4 and delete4. I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs). This resulted in the following code.
$(function() {
initJQueryPlugins();
$('#add').on('click', function() {
$last_row = $('#table1 > tbody > tr').last();
if(!hasValues($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row($('#table1'));
}
});
$('#delete').on('click', function() { delete_row($('#table1')); });
$('#add4').on('click', function() {
$last_row = $('#table4 > tbody > tr').last();
if(!hasValues4($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row4($('#table4'));
}
});
$('#delete4').on('click', function() { delete_row4($('#table4')); });
});
function add_row($table) {
var tr_id = $table.find('tr').length - 1;
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".selectType", $tr).select2({
tags: true
});
}
function hasValues($row){
$optVal = $row.find('td option:selected').text();
$inputVal = $row.find('td input').val();
$textVal = $row.find('td textarea').val();
if($optVal != "" || $inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row($table) {
var curRowIdx = $table.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function add_row4($table4) {
var tr_id = $table4.find('tr').length - 1;
var $template = $table4.find('tr.template4');
var $tr = $template.clone().removeClass('template4').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table4.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
}
function hasValues4($row4){
$inputVal = $row4.find('td input').val();
$textVal = $row4.find('td textarea').val();
if($inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row4($table4) {
var curRowIdx = $table4.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function initJQueryPlugins() {
add_row($('#table1'));
add_row4($('#table4'));
}
I have set up a working FIDDLE
The problem is this. If you start adding a few rows in the first table, this all works fine. After this, add a few rows in the second table. This seems to work fine. However, now start deleting rows in the second table. For some reason it seems to also delete rows in the first table.
So my main question is why does this happen? Additionally, is there any way I can do this without duplicating the code? The second table does not use select2.
Thanks
You are deleting this:
$("#" + (curRowIdx - 1)).remove();
This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();
or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()
I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/

jQuery put content of textbox inside a div

This is the html markup
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js">
</script>
<style type="text/css">
div{ padding:4px; }
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(
function() {
var counter = 2;
$('a.add').live('click', function() {
if (counter > 5) {
alert("Only 5 textboxes allowed");
return false;
}
var newRow =
$(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
var i = 0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
$(this).text('Remove').removeClass('add').addClass('remove');
counter++;
});
$('a.remove').live('click', function() {
$(this).closest('tr').remove();
counter--;
var i=0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
});
$("#getButtonValue").click(function() {
var test='';
for(var i=0;i<5;i++){
var minValue = $('#Col'+(i++)).val().trim();
var maxValue = $('#Col'+i).val().trim();
if((minValue=='' && maxValue !='')||(minValue!='' && maxValue !='' && minValue > maxValue)){
alert('Alerting...');
}
}
var gridInAnswerValuesHtml = "";
$(".grdAns").each(function() {
//ansString += this.value+",";
gridInAnswerValuesHtml += "<input type = \"hidden\" name = \"gridInAnswers\" value = \"";
gridInAnswerValuesHtml += this.value;
gridInAnswerValuesHtml += "\">";
});
alert(gridInAnswerValuesHtml);
});
});
</script>
</head>
<body>
<div id="blankDiv"></div>
<table id="gridInAnswers">
<tr>
<th>
Min Value
</th>
<th>
Max Value
</th>
</tr>
<tr>
<td>
<input type="text" name="col1" id="Col0" class="grdAns" />
</td>
<td>
<input type="text" name="col1" id="Col1" class="grdAns" />
</td>
<td>
Add
</td>
</tr>
<tr>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</tr>
</table>
</body>
on click of the add button I want to remove the textbox but its contents should get displayed say inside a div. i.e. I want to stop user from modifying this but disabling the textbox is not an option. How do I achieve this ?
Basically what you need to do is to do the replacement as soon as you click on the add link. The replacement is really simple.
// Do the magic here (Kuroir)
$(this).parent().parent().find('input').each(function(){
$(this).replaceWith('<div class="inactive">' + $(this).val() + '</div>');
});
Basically, you're going back to the tr level, then finding the input and doing the replacement for that row.
Working Solution: http://jsfiddle.net/kuroir/SXppg/
To get content from an <input> and place it in a <div>, you want something like:
$('#target-div-id').text(
$('#Col0').val()
);
I'm reasonably sure that's what you're trying to do.

Categories