Add data to a dynamic row from database - dynamic

So for example i have a form where the data is added dynamically. When I click on a "+" there comes one more row, where i can add more data. And so on...
Like in this example.
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/>
<table id="POITable" border="1">
<tr>
<td>POI</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Delete?</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td>
</tr>
</table>
So how can i save this data on a database, and then read this. I also need to save the count of the row´s. Is this even possible with JS?

Related

datatables sorting by selected checkboxes on top

I am trying to order checkboxes in a datatable at the top when they are clicked. This all works fine, but I also need to order them at the top when the page first loads. This I am having a struggle with. Any suggestions are appreciated!
$(document).ready(function() {
table = $('#schedule-list').DataTable( {
"dom": '<"toolbar">frtip',
"iDisplayLength": 500,
columnDefs: [
{ targets: 0, visible: false }
],
orderFixed: [0, 'desc'],
} );
$("#schedule-list_wrapper div.toolbar").html('<input class="btn btn-primary btn-sm md-btn-flat ml-3 checkall2" type="button" name="CheckAll2" id="checkall2" value="Select All" onClick="this.value=checkScheds(this.form)" style="float:left;">');
} );
$('#schedule-list').on('change', 'input[type="checkbox"]', function() {
var row = table.row($(this).closest('tr'));
table.cell({ row: row.index(), column: 0 } ).data( this.checked ? 1 : 0 )
row.invalidate().draw()
})
var checkflag2 = false;
function checkScheds() {
var inputs = document.getElementsByClassName( 'schedule' );
checkflag2 = checkflag2 === false ? true : false;
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = checkflag2;
}
return checkflag2 === true ? "Deselect All" : "Select All";
}
Here is some table data:
<table id="schedule-list" class="table table-striped" style="border-style: none; ">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<cfoutput>
<cfloop query="qryUserDetail.schedulelist">
<tr>
<td></td>
<td>
<label class="custom-control custom-checkbox">
<cfif structKeyExists(form, 'schedule') and #ArrayContains(form.schedule,#id#)# or (structKeyExists(url, 'schedule') and #url.schedule# eq #id#)>
<input type="checkbox" class="custom-control-input schedule" value="#id#" name="schedule" id="schedule" checked>
<cfelse>
<input type="checkbox" class="custom-control-input schedule" value="#id#" name="schedule" id="schedule">
</cfif>
<span class="custom-control-label">#schedname#</span>
</label>
</td>
</tr>
</cfloop>
</cfoutput>
</tbody>
</table>

get element id from template using smarty - Prestahop

I'm using Smarty in Prestashop. In my php file I built a function like this:
public function hookDisplayAdminOrderContentOrder($params)
{
$orderId = Tools::getValue('id_order'); // mi prendo l'id dell'ordine per le query sui docId
$query = 'SELECT docId1, docId1 FROM '._DB_PREFIX_.'orders WHERE id_order=\'' . $orderId . '\';';
$docId2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docId2'];
$docId1 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docId1'];
$config_CreaOrdine = Configuration::get('PS_CREAZIONE_ORDINE');
$config_CreaFattura = Configuration::get('PS_CREAZIONE_FATTURA');
// uso order_documents per il contatore nel template
$order_documents = 0;
if ($docId1 || $docId2)
$order_documents++;
else if ($docId1 && $docId2)
$order_documents = 2;
if(!$docId1){
$message_order = 'documento NON salvato';
$submit_button_id = 'submit_order';
$submit_label = "Salva Ordine";
}else{
$message_order = 'documento salvato';
}
if(!$docId2){
$message_invoice = 'documento NON salvato';
$submit_button_id = 'submit_invoice';
$submit_label = "Salva Fattura";
}else {
$message_invoice = 'documento salvato';
}
smartyRegisterFunction($this->context->smarty, 'function', 'saveDocument', array($this, 'smartyDocument')); // aggiungo la funzione per salvare di nuovo l'ordine
$this->context->smarty->assign('id_order', $orderId);
$this->context->smarty->assign('config_CreaOrdine', $config_CreaOrdine);
$this->context->smarty->assign('config_CreaFattura', $config_CreaFattura);
$this->context->smarty->assign('order_documents', $order_documents); // contatore documenti salvati
$this->context->smarty->assign('order', $message_order);
$this->context->smarty->assign('order_docId', $docId1); //docId per tasto ordine
$this->context->smarty->assign('invoice', $message_invoice);
$this->context->smarty->assign('invoice_docId', $docId2); //docId per tasto fattura
return $this->display(__FILE__, 'views/templates/hook/admin_content_order.tpl');
}
Then in my admin_content_order.tpl I set the button name and id like this:
<div class="tab-pane" id="myplugin">
<table>
<tbody>
<thead>
<tr>
<td style="padding-left: 20px;"><strong>{l s='Stato ordine' mod='myplugin'} </strong></td>
<td style="padding-left: 20px;"><strong>{l s='Stato fattura' mod='myplugin'} </strong></td>
</tr>
</thead>
<tr>
<td style="padding-left: 20px;">{$order}</td>
<td style="padding-left: 20px;">{$invoice}</td>
</tr>
<tr>
<td style="padding-left: 20px;">
{if $order_docId == '' && $config_CreaOrdine eq 1}
<button type="submit" name="submit_order" id="submit_order" class="btn btn-primary" onclick={saveDocument}>Salva Ordine</button>
{/if}
</td>
<td style="padding-left: 20px;">
{if $invoice_docId == '' && !$config_CreaFattura eq 0}
<button type="submit" name="submit_invoice" id="submit_invoice" class="btn btn-primary" onclick={saveDocument}">Salva Fattura</button>
{/if}
</td>
</tr>
</tbody>
</table>
</div>
At last in my php file I define the function "smartyDocument". I wish a slight different behaviour of it, based on the button id. Anyone knows how I can I get the button id and pass it to "smartyDocument" function? I hope is all clear, thx
You cannot use any Smarty commands after loading the page. You can use the Javascript function instead.
Smarty is a server-side engine and the output is sent to the browser after processing, which is quite static.
You have to have a Javascript function to save your document by Ajax:
send your data to PHP
save data
return success or fail message

Is there a way to sort by the content inside an input box in vuejs?

I am making a data table where I shall show diffrent users information. I want to be able to sort for an example all the users by their firstname or lastname. I have used inputboxes becuse I also want to be able to edit the users information.
I have tried diffrent scripts from here on stackoverflow and other sites. But to no sucess. tried template and even copied straight off a working code but with out inputboxes then. I am also very new to Vue js only worked with it for 4 days.
<div id="app">
<table class="table">
<thead>
<tr>
<!--Rubriker för tabellkolummer-->
<th>ID</th>
<th>Förnamn</th>
<th>Efternamn</th>
<th>Telefonnummer</th>
<th>E-postadress</th>
<th>Behörighet</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(user,index) in users">
<template v-if="user && user.editable">
<td><input type="text" v-model="user.uuid" class="input" disabled></td>
<td><input type="text" v-model="user.firstName" class="input"></td>
<td><input type="text" v-model="user.lastName" class="input"></td>
<td><input type="text" v-model="user.phone" class="input"></td>
<td><input type="text" v-model="user.email" class="input"></td>
<td><input type="text" v-model="user.jobTitle" class="input"></td>
<td><button class="button" #click="onUserClick(index)">Spara</button>
<button class="button" #click="tabortrad(index)">Ta bort rad</button></td>
</template>
<template v-else>
<td><input type="text" v-model="user.uuid" class="input" disabled></td>
<td><input type="text" v-model="user.firstName" class="input" disabled></td>
<td><input type="text" v-model="user.lastName" class="input" disabled></td>
<td><input type="text" v-model="user.phone" class="input" disabled></td>
<td><input type="text" v-model="user.email" class="input" disabled></td>
<td><input type="text" v-model="user.jobTitle" class="input" disabled></td>
<td><button class="button" #click="onUserClick(index)">Redigera</button>
<button class="button" #click="tabortrad(index)">Ta bort rad</button></td>
</template>
</tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th><button class="button is-pulled-right" #click='laggtillrad(users)'>Lägg till en rad</button></th>
</tbody>
</table>
</div>
<script>
faker.locale = "sv";
//Skapar slumpmässiga användardata
let randomusers = [];
for (i = 0; i < 4; i++) {
let uuid = faker.random.uuid();
let firstName = faker.name.firstName();
let lastName = faker.name.lastName();
let phone = faker.phone.phoneNumber();
let email = faker.internet.email();
let jobTitle = faker.name.jobTitle();
randomusers.push({ 'uuid': uuid, 'firstName': firstName, 'lastName': lastName, 'phone': phone, 'email': email, 'jobTitle': jobTitle });
}
new Vue({
el: '#app',
data: {
users: randomusers,
},
methods: {
//Lägger till en rad längst ner i tabellen
laggtillrad: function (event) {
var nyrad = {
uuid: faker.random.uuid(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
phone: faker.phone.phoneNumber(),
email: faker.internet.email(),
jobTitle: faker.name.jobTitle(),
};
this.users.push(nyrad)
},
//Tar bort raden där användaren trycker på "Ta bort" knappen
tabortrad: function (index) {
this.users.splice(index, 1);
},
//Redigerar raden där användaren trycker på "Redigera" knappen och ersätts med en spara knapp
onUserClick(index) {
const changeUser = this.users[index];
changeUser.editable = !changeUser.editable;
this.$set(this.users, index, changeUser);
}
},
})
</script>
I just want to be able to sort the users information. But think I must start all over again an use something called grid I think. But if someone can help me I will be very happy and maybe some off this code I have can come to use for someone else :).
Just add sortedUsers computed property that returns the sorted copy of users array and use it this way:
<tr v-for="(user,index) in sortedUsers"> and
computed: {
sortedUsers() {
// Using destructuring to prevent users array in-place mutation
return [...this.users].sort((userA, userB) => userA.firstName.localeCompare(userB.firstName))

How to set header value in kendo grid row template

I am using jquery kendo grid in my project where i used row template to show three column in one row. Below is the code:
<table id="grid" style="width:100%">
<thead style="display:none">
<tr>
<th>
Details
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3"></td>
</tr>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<div>
<span class="name" style="font-size:medium">#: FirstValue #</span>
<span class="name" style="font-size:medium">#: SecondValue #</span>
</div>
<tr>
<td style="width:30%">
#: GetName #
<span class="name" style="font-size:14px; color:green">#: Designation #</span>
<span class="name" style="font-family:Arial; font-size:small">#: Company #</span>
</td>
</tr>
</script>
in the above code i am just passing my model data it's working fine but when i added one div which have value firstName and LastName so it is also repeating with this data but i want to to show separately.How do i show it separately so that it should not repeat with grid.
there is one problem in your html template.
Please replace '#' with 'Javascript:void(0)'.
Error:- #: GetName #
Fix:- #: GetName #
Hope that's work for you.
http://jsfiddle.net/parthiv89/t0w3ht6m/1/
if you like then don't forget to like.
I got solution by own, Firstly i changed code in my schema like this:
schema: {
parse: function (data) {
var items = [];
for (var i = 0; i < data.data.length; i++) {
if (data.data[i].CorrectValue != null && data.data[i].SearchValue != null) {
$("#spnSR")[i].innerHTML = "<b>"+"Get results for this text: "+"</b>"+data.data[i].CorrectValue;
$("#spnSV")[i].innerHTML = "<b>" + "Searched for this text: " +"</b>" + data.data[i].SearchValue;
}
}
var product = {
data: data.data,
total: data.total
};
items.push(product);
return (items[0].data);
},
}
Then in html i used two span to show this value which is there in for loop.
and it's working fine for me.
Thanks everyone.

Can datatables sort a column with an input field?

I am trying to make datatables sort my columns. The first column works okay as it's a simple number. However the next column is an input field. When I try to make that sort then nothing happens.
<table width="100%" cellspacing="0" class="table sortable no-margin">
<thead>
<tr>
<th scope="col" class="sorting" style="width: 57px;">
<span class="column-sort">
</span>
ID
</th>
<th scope="col" class="sorting_desc" style="width: 94px;">
<span class="column-sort">
</span>
Order
</th>
</tr>
</thead>
<tbody>
<tr id="row_20" class="odd">
<td id="refKey_20" style="text-align:center;" class="">
1Y
</td>
<td class=" sorting_1">
<input type="text" value="160" size="3" name="item.Order"
maxlength="3" id="Order_20" >
</td>
</tr>
<tr id="row_19" class="even">
<td id="refKey_19" style="text-align:center;" class="">
1X
</td>
<td class=" sorting_1">
<input type="text" value="150" size="3" name="item.Order"
maxlength="3" id="Order_19" >
</td>
</tr>
</tbody>
</table>
Is there some way that I can get datatables to sort input fields?
The easiest way is to add a hidden span inside columns <span style="visibility:hidden">value of the input</span>
You should look at this example that explains how to do sorting on input fields. Basically you declare a sorting function
/* Create an array with the values of all the input boxes in a column */
$.fn.dataTableExt.afnSortData['dom-text'] = function ( oSettings, iColumn )
{
var aData = [];
$( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
aData.push( this.value );
} );
return aData;
}
And then tell to your table to use that
$('#example').dataTable( {
"aoColumns": [
null,
{ "sSortDataType": "dom-text" }
]
} );
or wit aoColumnDefs
$('#example').dataTable( {
"aoColumnDefs": [{ "sSortDataType": "dom-text" , aTarget: "yourclass"}]
} );
For versions of Datatables 1.10+ the names of some option variables have been changed and a new API introduced. Documentation here: http://datatables.net/examples/plug-ins/dom_sort.html.
Here is a working version of the above accepted answer in 1.10+:
$(document).ready(function () {
var table = $('#example').DataTable({
"columnDefs": [
{
"orderDataType": "dom-input",
"targets": 0, // Just the first column
},
],
});
});
The custom sort function:
$.fn.dataTable.ext.order['dom-input'] = function (settings, col) {
return this.api().column(col, { order: 'index' }).nodes().map(function (td, i) {
return $('input', td).val();
});
}
jQuery.fn.dataTableExt.oSort['textbox-asc'] = function (a, b) {
var vala = $('#' + $(a).filter('input').attr('id')).val().toLowerCase();
var valb = $('#' + $(b).filter('input').attr('id')).val().toLowerCase();
if (vala === '')
return 1;
if (valb === '')
return -1;
return vala < valb ? -1 : vala > valb ? 1 : 0;
};
jQuery.fn.dataTableExt.oSort['textbox-desc'] = function (a, b) {
var vala = $('#' + $(a).filter('input').attr('id')).val().toLowerCase();
var valb = $('#' + $(b).filter('input').attr('id')).val().toLowerCase();
if (vala === '')
return 1;
if (valb === '')
return -1;
return vala < valb ? 1 : vala > valb ? -1 : 0;
};
then use it like this
$(datatable).dataTable({
"iDisplayLength": 50,
"bLengthChange": false,
"bPaginate": false,
"columns": [
null, { "sType": "textbox" }
],
});
If you decide to use the columns option where you are rending information from a JSON file you can easily add a hidden span on your render property. It appears as though DataTables looks for text to order and if it cannot find any, it will break. The example at https://datatables.net/examples/plug-ins/dom_sort.html uses a table that has already been rendered. Here is an example using an API:
...columns([{
"data": "receivedDate",
"render": function (data, type, row, meta)
{
if (data == "null")
{
return "<input type='text' id='datepicker_" + meta.row + "' class='datepicker form-control' /><span class='hidden'><span>";
}
else
{
return "<input type='text' id='datepicker_" + meta.row + "' class='datepicker form-control' value='" + moment(data).format("MM/DD/YYYY") + "'/><span class='hidden'>" + moment(data).format('MM/ DD / YYYY') + "</span>";
}
}
}]);
Set an invisible div with the value before the input field.
<tbody>
<tr id="row_20" class="odd">
<td id="refKey_20" style="text-align:center;" class="">
1Y
</td>
<td class=" sorting_1">
<div style="display:none;">160</div>
<input type="text" value="160" size="3" name="item.Order"
maxlength="3" id="Order_20" >
</td>
</tr>
<tr id="row_19" class="even">
<td id="refKey_19" style="text-align:center;" class="">
1X
</td>
<td class=" sorting_1">
<div style="display:none;">150</div>
<input type="text" value="150" size="3" name="item.Order"
maxlength="3" id="Order_19" >
</td>
</tr>
</tbody>