How to prevent table row height glitch during DOM append? - javascript

I load my table first, then I dynamically append tags asynchronously.
As soon as those tags are appended, the table row height seems to shift up. How can I prevent that ?
I've tried
.portfolio-table tr {
height: 80px;
}
Table
<table class="table portfolio-table">
<thead class="thin-border-bottom">
<th width="2%">#</th>
<th width="28%">Name</th>
<th width="60%" class="text-left">Tags</th>
<th width="5%">Edit</th>
<th width="5%">Delete</th>
</thead>
<tbody>
<tr>
#foreach ($portfolios as $portfolio)
<td title="{{ $portfolio->id }}">{{ $portfolio->id }} </td>
<td>
<a href="/portfolio/{{ $portfolio->id ?? '' }}/">
{{ $portfolio->name }}
</a>
</td>
<td class="text-right" >
<img src="/assets/fe/img/svg/default.svg" alt="Loading" width="30px">
<p class="portfolioSkillTags text-left" id="{{ $portfolio->id ?? '' }}"></p>
</td>
<td>
<a href="/portfolio/{{ $portfolio->id ?? '' }}/edit" type="button" class="btn btn-info btn-sm">
Edit
</a>
</td>
<td>
<a data-toggle="modal" data-target="#delete_portfolio_{{ $portfolio->id ?? '' }}" type="button" class="btn btn-danger btn-sm">
Delete
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
ajax
$("tbody").each(function(){
$($(this)).find('tr').each(function(){
var selector = $(this);
var id = $(this).find('td:nth-child(1) ').attr('title');
// console.log('%c id = ' + id, "color: green;");
// return false;
var data = {};
data.id = id;
$.ajax({
method: 'POST',
url: '/api/portfolio/' + id + '/skills',
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(response){
console.log(id, response);
$('p.portfolioSkillTags#'+ id).prev('img').fadeOut();
for (i = 0; i < response.length; i++) {
// console.log(response[i],id);
var name = response[i]['name'];
var color = response[i]['color'];
$('p.portfolioSkillTags#'+id).prepend('<span class="badge" style="background-color:' + hexToRgb(color,.2) + ';border:' + hexToRgb(color,.7) + ' 2px solid;">' + name + '</span>').fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});

It seems the loading spinner image causes the glitch since it makes the text oveerflow. You can try fix it with some css style like float right so it wont make the paragraph wrap.
<img src="/assets/fe/img/svg/default.svg" style="float: right;" alt="Loading" width="30px">

The issue is with the height of the spinner (svg element). When you loads the data asynchronously, it brings the spinner with larger height. As soon as your API call resolves successfully, the spinner element (which has larger height goes away). Then your other data that can be retained in less height shrinks and produces this issue.
You can fix it with many ways, the simplest one is, keep the height(including paddings) of spinner (svg) element smaller than height of td element. For example:
<img src="/assets/fe/img/svg/default.svg" alt="Loading" width="30px" height="30px">
.portfolio-table tr td {
height: 50px;
}
UODATE
Please rectify the HTML as well, you might want to start the foreach loop outside the start tag of tr HTML element.
#foreach ($portfolios as $portfolio)
<tr>
<td title="{{ $portfolio->id }}">{{ $portfolio->id }} </td>
<td>
<a href="/portfolio/{{ $portfolio->id ?? '' }}/">
{{ $portfolio->name }}
</a>
</td>
<td class="text-right" >
<img src="/assets/fe/img/svg/default.svg" alt="Loading" width="30px">
<p class="portfolioSkillTags text-left" id="{{ $portfolio->id ?? '' }}"></p>
</td>
<td>
<a href="/portfolio/{{ $portfolio->id ?? '' }}/edit" type="button" class="btn btn-info btn-sm">
Edit
</a>
</td>
<td>
<a data-toggle="modal" data-target="#delete_portfolio_{{ $portfolio->id ?? '' }}" type="button" class="btn btn-danger btn-sm">
Delete
</a>
</td>
</tr>
#endforeach

$('p.portfolioSkillTags#'+ id).prev('img').fadeOut();
make this to
$('p.portfolioSkillTags#'+ id).prev('img').hide();
and Please rectify the HTML as well, you might want to start the foreach loop outside the start tag of tr HTML element as mentioned by Prince

I think the problem is a css animation. Try something to globally enforce to disable them to see if the behavior disappear.
* {
animation: none !important;
}
If that is the case disable the animation with the right css selector when you are loading your data.

Related

passing variable value to href argument

I'm sure this is an easy one but I'm really stuck here..
This is the code
<td id="id"></td>
<td id="sku"></td>
<td id="name"></td>
<td id="type"></td>
<td id="price"></td>
<td id="shipping"></td>
<td id="description"></td>
<td id="image"></td>
<td>
<a href="/update-user?id=" </a>
</td>
<td>
<a class="btn border delete" data-id= > </a>
</td>
I need to pass the value that's gonna be in the id="id" to the href id and data-id
The table is populated by this function here
var i = 0;
function next(){
i++;
var value = $.ajax({
type: "get",
url: "http://localhost:3000/api/users",
dataType: 'json'
}).done(function (users) {
console.log(users[i]);
$('#id').text(users[i]._id)
$('#sku').text(users[i].sku)
$('#name').text(users[i].name)
$('#type').text(users[i].type)
$('#price').text(users[i].price)
$('#shipping').text(users[i].shipping)
$('#description').text(users[i].description)
$('#image').html("<img src='"+users[i].image+"'/>")
});
return value.responseJSON;
}
Many thanks everyone!
Is this what u mean? 馃暥
Only when there is 1 link on the page this will work, would advice you to use a class or id for the targeting. Like the way we did for .delete. Else every a href will be changed.
var i = 0;
function next(){
i++;
var value = $.ajax({
type: "get",
url: "http://localhost:3000/api/users",
dataType: 'json'
}).done(function (users) {
console.log(users[i]);
var uID = users[i]._id;
$('#id').text(users[i]._id)
$('#sku').text(users[i].sku)
$('#name').text(users[i].name)
$('#type').text(users[i].type)
$('#price').text(users[i].price)
$('#shipping').text(users[i].shipping)
$('#description').text(users[i].description)
$('#image').html("<img src='"+users[i].image+"'/>")
$('a').attr("href", "/update-user?id="+uID)
$('.delete').attr('data-id', uID)
});
return value.responseJSON;
}
<td id="id"></td>
<td id="sku"></td>
<td id="name"></td>
<td id="type"></td>
<td id="price"></td>
<td id="shipping"></td>
<td id="description"></td>
<td id="image"></td>
<td>
<a href="/update-user?id=" </a>
</td>
<td>
<a class="btn border delete" data-id= > </a>
</td>
Give the anchor a class.
<td>
<a class="link" href="/update-user?id=" </a>
</td>
then you can access it and updates its href
`$("#table tr").eq(i).find(".link").attr('href', '/update-user?id=' + users[i]._id);
You can do similarly with the data-id attribute of the delete button.

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

pass a twig variable as a parameter for a javascript function

I have a datatable that I need to add rows dynamically throught t.row.add(), the table is composed by 4 columns, one of them has buttons inside, those buttons are Show & Edit, and they need the {{ row.id }} so the can be shown or edit, the problem is that I don't know how get the twig variable works. Here is my table code:
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th class="table-checkbox noprint" style="text-align:center;">
<input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" disabled/>
</th>
<th width="40%" style="text-align:center;">
Valoraciones
</th>
<th width="20%" style="text-align:center;">
Estado
</th>
<th width="20%" style="text-align:center;" class="noprint">
Acciones
</th>
</tr>
</thead>
<tbody>
{% for valoracion in valoracion %}
<tr class="odd gradeX" id="fila{{ valoracion.id }}">
<td class="noprint">
<input type="checkbox" class="checkboxes" disabled/>
</td>
<td style="text-align:center;" id="valoracion">
{{ valoracion.descripcion }}
</td>
{% if valoracion.enabled == 1 %}
<td style="text-align:center;" id="estadoValEnable">Activo</td>
{% else %}
<td style="text-align:center;" id="estadoValEnable">Inactivo</td>
{% endif %}
<td style="text-align:center;" class="noprint">
<a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion({{valoracion.id}})">Ver</a>
<a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails({{valoracion.id}})">Editar</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
and here is the action to create a new row (the create action is in a modal view):
function sendDataCreateValoracionDetails() {
if ($('#CrearValoracionMantenimiento').val() == "") {
Notificacion("error", "La descripi贸n de la competencia no puede estar vac铆a");
$('#CrearValoracionMantenimiento').focus();
} else {
$.blockUI({
baseZ: 20000,
message: '<h4><img src="{{ asset('
assets / global / plugins / cubeportfolio / cubeportfolio / img / cbp - loading.gif ') }}" /> Guardando datos, por favor espere...</h4>'
});
var form = document.getElementById("formCreateMantenimientoValoracionDetails");
var formData = new FormData(form);
$.ajax({
url: '{{ path('
createValoracionMantenimiento ') }}',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
if (returndata.success == true) {
$.unblockUI();
$('#crearValoracion').modal('hide');
Notificacion("success", "Valoraci贸n RP", "Los datos se han guardado correctamente.");
if ($('#EstadoValoracion').attr('checked')) {
var status = "Activo";
} else {
var status = "Inactivo";
}
$(document).ready(function() {
var t = $('#sample_2').addClass('centro').DataTable();
$("#sample_2").each(function() {
t.row.add([
'<tr>' +
'<td><input type="checkbox" class="checkboxes" disabled/></td>',
'<td>' + ($("#CrearValoracionMantenimiento").val()) + '</td>',
'<td>' + status + '</td>',
'<td ><a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion(' {
{
valoracion.id
}
}
')">Ver</a><a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails(' {
{
valoracion.id
}
}
')">Editar</a></td></tr>',
]).draw(false);
});
});
} else {
if (returndata.success == false) {
$.unblockUI();
Notificacion("error", "Valoraci贸n RP", "Existe una valoraci贸n igual.");
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Notificacion("error", "Valoraci贸n RP", "Ha existido un problema y no se ha podido crear la valoraci贸n.");
$.unblockUI();
}
});
}
}
These are my buttons:
<a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion('{{ valoracion.id }}')">Ver</a>
<a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails('{{ valoracion.id }} ')">Editar</a>
and these are the twig parameters I need to pas inside the functions:
onclick="showMantenimientoValoracion('{{ valoracion.id }}') ///
onclick="editMantenimientoValoracionDetails('{{ valoracion.id }} ')`
here is the function code:
if ($('#EstadoValoracion').attr('checked')) {
var status = "Activo";
} else {
var status = "Inactivo";
}
$(document).ready(function() {
var t = $('#sample_2').addClass('centro').DataTable();
$("#sample_2").each(function() {
t.row.add([
'<tr>' +
'<td><input type="checkbox" class="checkboxes" disabled/></td>',
'<td>' + ($("#CrearValoracionMantenimiento").val()) + '</td>',
'<td>' + status + '</td>',
'<td ><a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion(' {
{
valoracion.id
}
}
')">Ver</a><a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails(' {
{
valoracion.id
}
}
')">Editar</a></td></tr>',
]).draw(false);
});
});
Thanks everyone :)
A twig variable can be readed by using .twig extension to the file name ends , When I need to use a variable twig inside javascript function, I create it inside file twig. There is not another way.
Just remove the quotes from the twig variable -
onclick="showMantenimientoValoracion('{{ valoracion.id }}')
should be
onclick="showMantenimientoValoracion({{ valoracion.id }})
And in your javascript function add the parameter -
function sendDataCreateValoracionDetails(valoracion_id) {
console.log(valoracion_id)
// Your code goes here
}
This should do it.

Editable multiple forms on a table

I am using editable plugin to preform in place edit
This is the code I am using that I got from their Doc page, it is supposed to be used for adding new records, But I want to use it to modify records)
<script>
$(document).ready(function() {
//init editables
$('.myeditable').editable({
url: '/post',
placement: 'right'
});
//make username required
$('#new_username').editable();
//automatically show next editable
$('.myeditable').on('save.newuser', function(){
var that = this;
setTimeout(function() {
$(that).closest('td').next().find('.myeditable').editable('show');
}, 500);
});
//create new user
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/newuser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
//set pk
$(this).editable('option', 'pk', data.id);
//remove unsaved class
$(this).removeClass('editable-unsaved');
//show messages
var msg = 'New user created! Now editables submit individually.';
$('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
$('#save-btn').hide();
$(this).off('save.newuser');
} else if(data && data.errors){
//server-side validation error, response like {"errors": {"username": "username already exist"} }
config.error.call(this, data.errors);
}
},
error: function(errors) {
var msg = '';
if(errors && errors.responseText) { //ajax error, errors = xhr object
msg = errors.responseText;
} else { //validation error (client-side or server-side)
$.each(errors, function(k, v) { msg += k+": "+v+"<br>"; });
}
$('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
}
});
});
//reset
$('#reset-btn').click(function() {
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
$('#save-btn').show();
$('#msg').hide();
});
});
</script>
And this is the html
<tr>
<td>adel</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>sdqsd</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>dzadz</td>
<td>from me with love</td>
<td>anywhere</td>
<td>http://justawebsite.com</td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
Now everything works fine, Except if I edit one of the 2 first rows and hit Ok It will send the details of the last form http://justawebsite.com and sometimes it doesn't send anything, It is really messed up and I spent hours reading te documentation but I couldn't figure out the problem
As I said in my comment, you've got different elements with the same id, so the selectors won't work (id must be unique). Put them as class instead:
<tr>
<td>
adel
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
<a href="#" class="myeditable picture" data-type="text" data-name="picture" data-original-title="Enter Picture">
<img src="" />
</a>
</td>
<td width="10%">
<button class="btn btn-primary btn-sm save-btn">Ok</button>
<button class="btn btn-sm pull-right reset-btn">Reset</button>
</td>
</tr>
Here's a fiddle to get you started https://jsfiddle.net/virginieLGB/k2of9xor/1/
On there, you'll see that I've selected the editable elements you want to submit.
$('.save-btn').click(function() {
var that = $(this);
var allEditables = that.parents("tr").find(".myeditable"); // all ".myeditable" elements in the same "tr" as the ".save-btn" that was clicked on
allEditables.each(function() {
// here I've kept your code because I don't know what happens in your file, but maybe you need a bulk action
$(this).editable('submit', {
...
I don't know how your PHP file works, so don't know how you save your user and if you need to submit all fields at once or not. If so, you'll have to modify my answer a bit.
Have you tried refreshing it afterwards?
For me i noticed, that as soon as it was refreshed i got the result that i have been expecting, but only for one of them. However, i couldn't solve the problem yet.
Please let me know what kind of result you get.
Otherwise try debugging...disable one of the first rows and try it again..

Telerik rad combobox multiple column databinding

Iam new to telerik controls.I have anchor tag of "Show all Account.. " in footer template of radcombobox
<telerik:RadComboBox runat="server" ID="rcmdExpAc" TabIndex="22" EmptyMessage="" HighlightTemplatedItems="true"
AllowCustomText="true" Width="235" OnClientDropDownOpening="OnClientDropDownOpeningExpAc" OnClientDropDownClosing="OnClientDropDownClosingExpAc">
<ItemTemplate>
<div class="combo-item-template">
<table>
<tr>
<td style="width: 40px;">
<span> <%# Eval("colAccCode")%> </span>
</td>
<td style="width: 400px;">
<span> <%# Eval("colAccName")%> </span>
</td>
<td style="width: 110px;">
<span> <%# Eval("colAcTypeName")%></span>
</td>
</tr>
</table>
</div>
</ItemTemplate>
<FooterTemplate>
<a id="ExpenseAccount" class="blue" style="text-decoration: underline;" href="#signup" name="signup" rel="leanModal">New Account...</a>
<a id="ElnkShowIncomeAccount" class="blue" style="text-decoration: underline; cursor: pointer;" onclick="EShowAllOrPaymentAccount(this);" >Show All Accounts...</a>
</FooterTemplate>
</telerik:RadComboBox>`
On show all accounts click the ajax call is called and it is rebind with combobox but the combo box only bind one column from database ...here is the code for ajax call.....
function EShowAllOrPaymentAccount(event) {
var dropDown = $find("rcmdExpAc");
if (event.innerHTML == "Show All Accounts...") {
$.ajax({
url: "../Handlers/Expense.ashx",
type: 'GET',
data: {
rType: "GetAllPaymentAccRecord",
CompanyID: $('#compid').val()
},
dataType: 'json',
success: function (data) {
dropDown.clearItems();
$.each(data, function (indx, itm) {
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_value(itm.colAccId);
comboItem.set_text(itm.colAccCode);
dropDown.trackChanges();
dropDown.get_items().add(comboItem);
dropDown.commitChanges();
});
},
error: function (a, b, c) {
alert(a + " " + b + " " + c);
}
});
}
}
I want to bind Eval("colAccName")%>,Eval("colAccCode")%>,Eval("colAcTypeName")%> are earlier defined in radcombo . but i only find a way of binding one column against colAccID... Please guide me how to bind 3 column from database which are defined in template in this javascript code.
You should define a ClientItemTemplate as shown in this demo.
It is used when you create your combo items client-side.
You can also use Attributes to store additional info about the item (text, value + AccountType, AccountCode, etc.). The syntax can be also seen in the documentation.

Categories

Resources