hide table in div used as dropdown - javascript

I have developed multi column dropdown using div and table.
How to hide dropdown when click on html body or any other control.Any suggestions
<input type="text" id="mulitcolumn">
<div id="myDropdownGrid" class="dropdownGrid" style="overflow:hidden;overflow-y:auto; max-height: 400px;border-right:1px solid rgb(51, 102, 153)">
<table class="grid">
#foreach (var item in (IEnumerable<SelectListItem>)ViewBag.List)
{
<tr>
<td style="display:none">#item.Value</td>
<td>#(item.Text.Substring(1, item.Text.IndexOf(']') - 1))</td>
<td>#(item.Text.Substring(item.Text.IndexOf("] - ") + 3, item.Text.Length - (item.Text.IndexOf("] - ") + 3)))</td>
</tr>
}
</table>
</div>
$('#myDropdownGrid table tr').click(function ()
{
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
$('#myDropdownGrid table').toggle();
});

Try:
$('.dropdownGrid').on('click',function() {
$(this).addClass('activ');
$(this).find('.grid').show();
});
$('body').click(function(evt){
console.log(evt.target)
if(evt.target.class == "activ" || $(evt.target).closest('.activ').length) {
return; }
else {
$(this).removeClass('activ');
$(this).find('.grid').hide()
}
});

Related

How to update a table in html/js?

i have a select-tag, where i can select a charging station. Under the select-tag is a table, where the specifications of the charging station are displayed.
My problem is now: How can i update the table after selecting another charging station in the select tab?
Here's a picture of the view:
And the code:
var id = Model.ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId;
var stations = (IList < ChargingStation > ) ViewBag.Stations;
var station = stations.FirstOrDefault(s => s.Id == id);
SelectList list;
if (station != null) {
list = new SelectList(stations, "Id", "ModelName", Model.ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId);
} else {
list = new SelectList(ViewBag.Stations, "Id", "ModelName");
}
<select asp-for="ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId" class="selectpicker form-control" data-style="btn-dark" data-live-search="true"
asp-items="list" onchange="updateTable(#i,#j)" title="---Säule auswählen---">
</select>
<script>
function updateTable(i, j) {
document.getElementById("table-" + i + "-" + j).update();
}
</script>
<span asp-validation-for="ChargingZones[i].ChargingStationChargingZones[j].ChargingStation.ModelName" class="text-danger"></span>
<table id="table-#i-#j" class="table table-hover table-striped table-bordered" style="white-space: normal; text-align: center">
<tr>
<th>Stecker</th>
<th>Anzahl</th>
<th>Leistung</th>
<th>Gleichzeitig<br/>Gleichtstrom</th>
</tr>
#{
if (list.SelectedValue != null)
{
ChargingStation s = new ChargingStation();
foreach (var item in stations)
{
if (item.Id.ToString() == list.SelectedValue.ToString())
{
s = item;
}
}
foreach (ChargingPoint point in s.ChargingPoints)
{
<tr>
<td>#point.ConnectorType.GetDisplayName()</td>
<td>#s.ChargingPoints.Count</td>
<td>#point.ChargingPower kW</td>
<td>#s.ParallelChargingPoints</td>
</tr>
}
}
}
</table>

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 drag and drop a column into another

I am using: jquery.dataTables.js from: https://datatables.net
I am trying to drag and drop a column from one table to another.
EDIT:
so basically what I want to do is:
be able to drag and drop the names from table 2 into column called name in the table above
after drag and drop the name the same should disappear from the table 2.
case 2: if I add a new row using the button Add new Row
I need be able to drag a drop the names from table 2 into that column name too.
so basically I want to do a drag and drop just in the column not in the row.
I don't want create a new row just move the names from 1 table to another.
EDIT 2:
1- Can you drag/drop multiples values from Table #2 to Table #1?
no, the drag and drop will be possible just 1 by 1.
The drag and drop will be just possible after the user clicks in edit or add a new row.
so I will be able to replace names drom table 2 into the column names table 1
2- If no, the value dragged shall then replace the value where it is dropped?
yes
3- If yes,how should it work? Adding new rows with the other values blank?
no row need be added, we just need replace the column name.
how will works:
so after click in edit or add new row i will be able to drag a name from table 2 into column in
table 1.
few more resquests if possible:
if select the row in table 2, this row should be change the color, showing was selected. and in the table 1 collun name where this need be dropped need to change the color to show the
user can be dropped.
sample working here:
http://plnkr.co/edit/6sbmBzbXDzm4p6CjaVK0?p=preview
$(document).ready(function() {
var dataUrl = 'http://www.json-generator.com/api/json/get/ccTtqmPbkO?indent=2';
var options = [
{ key : 'option 1', value : 1 },
{ key : 'option 2', value : 2 },
{ key : 'option 3', value : 3 }
];
$(document).ready(function() {
var $table = $('#example');
var dataTable = null;
$table.on('mousedown', 'td .fa.fa-minus-square', function(e) {
dataTable.row($(this).closest("tr")).remove().draw();
});
$table.on('mousedown.edit', 'i.fa.fa-pencil-square', function(e) {
enableRowEdit($(this));
});
$table.on('mousedown', 'input', function(e) {
e.stopPropagation();
});
$table.on('mousedown.save', 'i.fa.fa-envelope-o', function(e) {
updateRow($(this), true); // Pass save button to function.
});
$table.on('mousedown', '.select-basic', function(e) {
e.stopPropagation();
});
dataTable = $table.DataTable({
ajax: dataUrl,
rowReorder: {
dataSrc: 'order',
selector: 'tr'
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}, {
data: 'delete'
}]
});
$table.css('border-bottom', 'none')
.after($('<div>').addClass('addRow')
.append($('<button>').attr('id', 'addRow').text('Add New Row')));
// Add row
$('#addRow').click(function() {
var $row = $("#new-row-template").find('tr').clone();
dataTable.row.add($row).draw();
// Toggle edit mode upon creation.
enableRowEdit($table.find('tbody tr:last-child td i.fa.fa-pencil-square'));
});
$('#btn-save').on('click', function() {
updateRows(true); // Update all edited rows
});
$('#btn-cancel').on('click', function() {
updateRows(false); // Revert all edited rows
});
function enableRowEdit($editButton) {
$editButton.removeClass().addClass("fa fa-envelope-o");
var $row = $editButton.closest("tr").off("mousedown");
$row.find("td").not(':first').not(':last').each(function(i, el) {
enableEditText($(this))
});
$row.find('td:first').each(function(i, el) {
enableEditSelect($(this))
});
}
function enableEditText($cell) {
var txt = $cell.text();
$cell.empty().append($('<input>', {
type : 'text',
value : txt
}).data('original-text', txt));
}
function enableEditSelect($cell) {
var txt = $cell.text();
$cell.empty().append($('<select>', {
class : 'select-basic'
}).append(options.map(function(option) {
return $('<option>', {
text : option.key,
value : option.value
})
})).data('original-value', txt));
}
function updateRows(commit) {
$table.find('tbody tr td i.fa.fa-envelope-o').each(function(index, button) {
updateRow($(button), commit);
});
}
function updateRow($saveButton, commit) {
$saveButton.removeClass().addClass('fa fa-pencil-square');
var $row = $saveButton.closest("tr");
$row.find('td').not(':first').not(':last').each(function(i, el) {
var $input = $(this).find('input');
$(this).text(commit ? $input.val() : $input.data('original-text'));
});
$row.find('td:first').each(function(i, el) {
var $input = $(this).find('select');
$(this).text(commit ? $input.val() : $input.data('original-value'));
});
}
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/bXcKDeAbyq?indent=2';
table = $('#example2').DataTable({
ajax: url,
order: [[ 0, "desc" ]],
rowReorder: {
dataSrc: 'place',
selector: 'tr'
},
columns: [ {
data: 'name'
}]
});
});
});
div.addRow {
line-height: 45px;
background-color: #fff;
padding-left: 10px;
border-bottom: 1px solid;
border-top: 1px solid #e5e5e5;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="//cdn.rawgit.com/DataTables/RowReorder/ce6d240e/js/dataTables.rowReorder.js"></script>
<link href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="//cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
<th>action</th>
</tr>
</thead>
</table>
<table id="new-row-template" style="display:none">
<tbody>
<tr>
<td>999</td> <!-- Use a large number or row might be inserted in the middle -->
<td>__NAME__</td>
<td>__COUNTRY__</td>
<td>
<i class="fa fa-pencil-square" aria-hidden="true"></i>
<i class="fa fa-minus-square" aria-hidden="true"></i>
</td>
</tr>
</tbody>
</table>
<br>
<div class="pull-right">
<button type="button" id="btn-cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btn-save" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
I've made some changes to your code. Try it out please to see whether this resolution is appropriate for you:
$(document).ready(function() {
var dataUrl = 'http://www.json-generator.com/api/json/get/ccTtqmPbkO?indent=2';
var options = [{
key: 'option 1',
value: 1
},
{
key: 'option 2',
value: 2
},
{
key: 'option 3',
value: 3
}
];
var rowCache = [];
function mouseUp(event) {
var ctrl = $(document.elementsFromPoint(event.clientX, event.clientY)).filter('input.border-highlight');
if (ctrl.length > 0 && rowCache.length > 0) {
var el = rowCache[0];
var data = el.row.data();
if (data.length > 0) {
ctrl.val(data[0].name);
el.row.remove().draw();
}
}
rowCache = [];
$('#example tr td:nth-child(2) input').removeClass('border-highlight');
}
$(document).ready(function() {
var $table = $('#example');
var dataTable = null;
$('body').mouseup(mouseUp);
$table.on('mousedown', 'td .fa.fa-minus-square', function(e) {
dataTable.row($(this).closest("tr")).remove().draw();
});
$table.on('mousedown.edit', 'i.fa.fa-pencil-square', function(e) {
enableRowEdit($(this));
});
$table.on('mousedown', 'input', function(e) {
e.stopPropagation();
});
$table.on('mousedown.save', 'i.fa.fa-envelope-o', function(e) {
updateRow($(this), true); // Pass save button to function.
});
$table.on('mousedown', '.select-basic', function(e) {
e.stopPropagation();
});
dataTable = $table.DataTable({
ajax: dataUrl,
rowReorder: {
dataSrc: 'order',
selector: 'tr'
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}, {
data: 'delete'
}]
});
$table.css('border-bottom', 'none')
.after($('<div>').addClass('addRow')
.append($('<button>').attr('id', 'addRow').text('Add New Row')));
// Add row
$('#addRow').click(function() {
var $row = $("#new-row-template").find('tr').clone();
dataTable.row.add($row).draw();
// Toggle edit mode upon creation.
enableRowEdit($table.find('tbody tr:last-child td i.fa.fa-pencil-square'));
});
$('#btn-save').on('click', function() {
updateRows(true); // Update all edited rows
});
$('#btn-cancel').on('click', function() {
updateRows(false); // Revert all edited rows
});
function enableRowEdit($editButton) {
$editButton.removeClass().addClass("fa fa-envelope-o");
var $row = $editButton.closest("tr").off("mousedown");
$row.find("td").not(':first').not(':last').each(function(i, el) {
enableEditText($(this))
});
$row.find('td:first').each(function(i, el) {
enableEditSelect($(this))
});
}
function enableEditText($cell) {
var txt = $cell.text();
$cell.empty().append($('<input>', {
type: 'text',
value: txt
}).data('original-text', txt));
}
function enableEditSelect($cell) {
var txt = $cell.text();
$cell.empty().append($('<select>', {
class: 'select-basic'
}).append(options.map(function(option) {
return $('<option>', {
text: option.key,
value: option.value
})
})).data('original-value', txt));
}
function updateRows(commit) {
$table.find('tbody tr td i.fa.fa-envelope-o').each(function(index, button) {
updateRow($(button), commit);
});
}
function updateRow($saveButton, commit) {
$saveButton.removeClass().addClass('fa fa-pencil-square');
var $row = $saveButton.closest("tr");
$row.find('td').not(':first').not(':last').each(function(i, el) {
var $input = $(this).find('input');
$(this).text(commit ? $input.val() : $input.data('original-text'));
});
$row.find('td:first').each(function(i, el) {
var $input = $(this).find('select');
$(this).text(commit ? $input.val() : $input.data('original-value'));
});
}
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/bXcKDeAbyq?indent=2';
table = $('#example2').DataTable({
ajax: url,
order: [
[0, "desc"]
],
rowReorder: {
dataSrc: 'place',
selector: 'tr'
},
columns: [{
data: 'name'
}]
});
table.on('mousedown', 'tbody tr', function() {
var $row = $(this);
var r = table.rows(function(i, data) {
return data.name == $row.children().first().text();
});
if (r[0].length > 0) {
$row.parents('table').find('tr').removeClass('highlight');
$row.addClass('highlight');
$('#example tr td:nth-child(2) input').addClass('border-highlight');
}
rowCache.push({
row: r
});
});
});
});
div.addRow {
line-height: 45px;
background-color: #fff;
padding-left: 10px;
border-bottom: 1px solid;
border-top: 1px solid #e5e5e5;
}
tr.highlight td {
background-color: #D0ECE7 !important;
}
.border-highlight {
border-color: #D0ECE7 !important;
border-width: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>
<link data-require="datatables#*" data-semver="1.10.12" rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
<th>action</th>
</tr>
</thead>
</table>
<table id="new-row-template" style="display:none">
<tbody>
<tr>
<td>999</td>
<!-- Use a large number or row might be inserted in the middle -->
<td>__NAME__</td>
<td>__COUNTRY__</td>
<td>
<i class="fa fa-pencil-square" aria-hidden="true"></i>
<i class="fa fa-minus-square" aria-hidden="true"></i>
</td>
</tr>
</tbody>
</table>
<br>
<div class="pull-right">
<button type="button" id="btn-cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btn-save" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
JSFiddle: http://jsfiddle.net/f7debwj2/47/
First thing first, bind click event for table 2 td to grab the data which is really simple. Then I would write mouseup function as follows on table 1:
$('table-id-class').on('mouseup', 'td', function (e) {
console.log(e.html());
e.stopPropagation();
});
The above event would give you exact position of the td, you are left with changing value for the TD. I am sure datatables must be having some way to change values in order to go that value in data. Good luck!

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/

Making an editable dropdown and populating it from an external JS

I want to make an editable dropdown, and on double click of the data the dropdown should appear and make populate the options from and external JS, this should be made to run more than once.
The following is the HTML for this
<div class="tabbable">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<table id='table-draggable1'>
<tbody class="connectedSortable">
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
<tr>
<td>156</td>
<td>668</td>
<td>100.95</td>
<td class="master">100.95</td> //editable dropdown
</tr>
<tr>
<td class="desc">256</td>
<td>668</td>
<td>100.95</td>
<td class="master">100.95</td> // ondblclick should be editable
</tr>
</tbody>
</table>
</div>
</div>
</div>
The jquery which i tried for making the dropdown editable
$document.ready(function ()
{
dropdown();
$(function ()
{
$(".master").dblclick(function (e)
{
e.stopPropagation();
var currentEle = $(e.target);
var value = $(e.target).html();
console.log($(e.target));
if ($.trim(value) === "")
{
$(currentEle).data('mode', 'add');
}
else
{
$(currentEle).data('mode', 'edit');
}
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value)
{
$(currentEle).html("<select class='master'></select>");
var mode = $(currentEle).data('mode');
alert(mode);
$(".master").focus();
$(".master").keyup(function (event)
{
if (event.keyCode == 13)
{
$(this).parent().html($(this).val().trim());
$(".master").remove();
}
});
}
$(document).click(function (e)
{
if ($(".master") !== undefined)
{
if ($(".master").val() !== undefined)
{
$(".master").parent().html($(".master").val().trim());
$(".master").remove();
}
}
});
}
function dropdown()
{
var resp = "<option>" + 1 + "</option>"; //this should be populated in dropdown
$(".master").html(resp);
}
}
});
http://jsfiddle.net/tXakG/
You can accomplish this by using the datalist tag in HTML5.
<input type="text" name="product" list="productName"/>
<datalist id="productName">
<option value="a">Apple</option>
<option value="o">Orange</option>
<option value="b">Banana</option>
</datalist>
If you double click on the input text in the browser a list with the defined option will appear.
Added using javascript : data is conceded that taken from server through ajax
http://jsfiddle.net/rajaveld/7yM6V/
Else you can use jquery :
You can refer is jQuery UI for the same.

Categories