I have a problem with Datatables oLanguage.sInfo. When there are more than 999 entries, the variable TOTAL is wrong.
The main problem is that there is a string undefined inserted.
Eg, it shows not 1 to 50 of 5,601 entries but 1 bis 50 von 5undefined601
$.extend(
$.fn.dataTable.defaults,
{ "oLanguage": { "sInfo": "START bis END von TOTAL Einträgen", ...
}
});
DataTables 1.10.7
More details: http://debug.datatables.net/iqifax
I found how to fix this:
"oLanguage": {
"sThousands": ".",
Related
It happens that I have used the minDate option to deactivate the days before the current one to avoid selecting a date already in the past. This works perfectly for me in the create but in the update it does not show me the time, only the empty widget appears, although in the database it shows that the date was registered. I would like to know what error may be happening.
Rules
[['inicio_clase', 'fin_clase'], 'default', 'value' => function () {
return date(DATE_ISO8601);
}],
[['inicio_clase', 'fin_clase'], 'filter', 'filter' => 'strtotime', 'skipOnEmpty' => true],
[['inicio_clase', 'fin_clase','seccion_id', 'materia_id', 'estado'], 'integer'],
['inicio_clase','compare','compareAttribute'=>'fin_clase','operator'=>'<','message'=>'La fecha de inicio debe ser menor que la fecha de finalización.'],
['fin_clase','compare','compareAttribute'=>'inicio_clase','operator'=>'>','message'=>'La fecha de fin no debe ser menor o igual que la fecha de inicio.'],
Form
<?php echo $form->field($model, 'fin_clase'(
DateTimeWidget::class,
[
'phpDatetimeFormat' => 'yyyy/MM/dd HH:mm',
'clientOptions' => [
'minDate' => new \yii\web\JsExpression('new Date()'),
]
]
) ?>
You are probably trying to edit record with fin_clase set to the date before current date. The DateTimeWidget is set to not allow the date before the current day so it won't be able to show date in past even if that value is stored in model.
For example if today is 2021-10-12 and the record's fin_clase is set to 2021-10-11 it won't be filled during edit.
To avoid that you should set minDate to allow the actual value stored in model.
'minDate' => $model->isNewRecord
? new \yii\web\JsExpression('new Date()')
: new \yii\web\JsExpression("new Date({$model->fin_clase})"),
Or you might want to allow all dates in past when editing record.
'minDate' => $model->isNewRecord
? new \yii\web\JsExpression('new Date()')
: false,
I'm currently learning JS/jQuery and thought I'd code a quiz for practice. While I managed to code the basics of the quiz I am struggling with a crucial part of my code.
In this quiz, I have an Array containing 10 objects. Each object has a question (String), options (Array), an answer (String) and a Boolean which indicates whether or not a question has been answered. Further, I filter this array to include only those elements, that haven't been asked/answered yet. However, this unansweredArr always contains 10 elements, even if I call the function again before asking the new question.
What I aim to do is the following:
Generate an array, that holds every question that hasn't been
answered yet. This is being done with
var unansweredArr = data.filter(function(question){
return question.answered === false;
});
Then I generate a random number, which will be used to grab an element out of this array. Said element then is being displayed in my HTML
When the player clicks on an option, the given answer will be checked. If correct, the player's score will be increased by 1 and the next question will be asked. Also answered: false will be set to answered: true on that specific question.
Until step 3, everything works like a charm (for me ;)) However, step 4 and further are my main problems.
Basically, step 2 and 3 should be repeated. Thus, the array should filter for every Object with answered: false. This array should update and contain 9 elements now - However, it doesn't. It still contains 10 elements and I don't know why. I tried to call the filter function again, without success. I tried refactoring some code by moving bits and pieces around, but nothing worked for me. Additionally, when checking for the right answer, it seems like the answer to the question that has been first answered is saved and will be used to for all the other questions.
Please find my code here:
var data = [{
question: "Cabrio: Check! Glas wird geext / Na klar gibt es Sex, weil ich parshippe jetzt!",
options: ["Gzuz", "Bonez MC", "RAF Camora", "LX"],
answer: "Gzuz",
answered: false
},
{
question: "Die Presse will mich mit Monsterbräuten in Bondfahrzeugen knipsen / Es ist wie Naturgewalten, weil Blitze vor dem Don erleuchten (Donner leuchten), Bitches!",
options: ["Kollegah", "Farid Bang", "Ali As", "Fatoni"],
answer: "Kollegah",
answered: false
},
{
question: "Frage: Was haben ein Rabbi, ein Priester, ein Koch mit 3 Eiern / ein Flyerverteiler mit einem Paket Flyern / ein Esel, zwei Geier, ich und 300 Freier gemeinsam? / Könnten alle dein Vadder sein!",
options: ["Snaga", "Pillath", "Torch", "KC Rebel"],
answer: "Snaga",
answered: false
},
{
question: "Denkt ihr, die Flüchtlinge sind in Partyboote gestiegen / mit dem großen Traum, im Park mit Drogen zu dealen?",
options: ["Tarek", "Maxim", "Nico", "DJ Craft"],
answer: "Tarek",
answered: false
},
{
question: "Rapper reden über Muskeln oder Brustumfang / Ich bin so ein Sklave, ich muss Benz fahren aus Gruppenzwang",
options: ["Shindy", "Bushido", "Fler", "Sido"],
answer: "Shindy",
answered: false
},
{
question: "Widerlich, Bitch! / Also glaub nicht, dass du Hund hier'n Aufreißer wirst (Hirn auf Reis servierst) wie'n China-Imbiss",
options: ["Kollegah", "Majo", "Jizi", "Gozpel"],
answer: "Kollegah",
answered: false
},
{
question: "Ich bin nicht nur der King dieser Mucke – ich bin diese Mucke!",
options: ["Kool Savas", "Eko Fresh", "Moe Mitchell", "Kaas"],
answer: "Kool Savas",
answered: false
},
{
question: "Ich brauch' Para, damit F*ckf*tzen blasen, ich muss Fixkosten tragen, die kann Rick Ross nicht zahlen.",
options: ["SSIO", "Schwester Ewa", "Xatar", "Abdi"],
answer: "SSIO",
answered: false
},
{
question: "Hater schauen und bauen sich einen Fake-Account, doch wissen, dass mein Album hitlastig ist/Hitlers Dick isst wie Eva Braun.",
options: ["Ali As", "Kollegah", "Farid Bang", "Majo"],
answer: "Ali As",
answered: false
},
{
question: "Dein Rap ist voller Tiefsinnigkeit/ Dass man als Zuhörer denkt, dein Schniedel ist klein",
options: ["SSIO", "Edgar Wasser", "Juse Ju", "Azad"],
answer: "SSIO",
answered: false
},
];
//Generate a score variable
var score = 0;
//Generate an array, which includes all the unanswered questions
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Random Number in order to get a random element from the array
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display random element/question in HTML
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
//What happens when the person answers the question
$(".Rapper").on("click", function() {
unansweredArr[randomIndex].answered = true;
var selected = $(this).text();
var trueAnswer = unansweredArr[randomIndex].answer;
//Check if answered correctly
if (auswahl === wahreAntwort) {
//Increase score by 1 and ask next question
console.log("Correct");
next();
return score = score + 1;
} else {
console.log("Wrong");
next();
return score;
}
});
function next() {
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Check if the array of unanswered questions is not empty
if (unansweredArr.length !== 0) {
//New random number
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display question and options in html
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
} else {
console.log("Game Over");
console.log(score);
}
}
/* Problems:
- unansweredArr does not update after a question has been answered.
- Answer to the first question will be the answer for the following questions.
*/
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
Zurück.
<div>
<!-- Frage Block -->
<div>
<p id="question">-- This is, where the punchline will be displayed --</p>
</div>
<!-- Antwort Möglichkeiten -->
<div>
<div>
Rapper 1
</div>
<div>
Rapper 2
</div>
<div>
Rapper 3
</div>
<div>
Rapper 4
</div>
</div>
</div>
The problem is that you define the same variables randomIndex and unansweredArr as global variables and as local variables in the function next.
When you update their value in the function next, the global variables with the same names do not change.
As a consequence you are always marking the first random question as answered:
unansweredArr[randomIndex].answered = true;
These are the global variables, and randomIndex does not reflect the most recently generated number.
Solution: remove the word var from before these variable names in the function next.
I did not check for other errors, but this one explains the behaviour you describe.
I created a table using jQuery. I added a row.child which shall be shown after each parent row. On the first page this works fine. But on the second page it is missing.
function format(d) {
return '' +
'<i style=";color:#9b9b9b; font-size:10px; Padding-left:50px"> Vertragsart - ' + d[4] + ' | Intensität - ' + d[5] + '</i>' +
'';
}
var $j = jQuery.noConflict();
$j('document').ready(function () {
var oTable = $j('#position_list').DataTable({
"order": [[0, "desc"]],
"iDisplayLength": 50,
"oLanguage": {
"sLengthMenu": "Zeige _MENU_ Einträge",
"sSearch": "Suche:",
"sInfo": "Zeige _START_ bis _END_ von _TOTAL_ Einträgen",
"sInfoEmpty": "Zeige _START_ bis _END_ von _TOTAL_ Einträgen",
"sInfoFiltered": "(gefiltert aus _MAX_ Datensätzen)",
"oPaginate": {
"sNext": "Nächste",
"sPrevious": "Vorherige"
},
},
});
$j('.parentrow').closest('tr').each(function () {
var row = oTable.row(this);
var data = format(row);
row.child(format(row.data())).show();
});
});
The problem is that you are using jQuery to select the rows, but jQuery only has access to the rows currently on the DOM. As it was said in the comments, only the rows of the current page are in the DOM at any given moment, so those are the only rows your code will manipulate.
To run a jQuery selector through the whole table, Datatables API has the $() method. It accepts a jQuery selector that will be run on all tr elements on the table and their descendant elements, returning a jQuery object like jQuery(selector) does.
So you only need to change your jQuery selector for oTable.$(...):
oTable.$('.parentrow').closest('tr').each(function () {
var row = oTable.row(this);
var data = format(row);
row.child(format(row.data())).show();
});
Use drawCallback option or draw event to call your code every time the table is redrawn.
For example:
$j('#position_list').on('draw.dt', function(){
$j('.parentrow').closest('tr').each(function(){
var row = oTable.row(this);
var data = format(row);
row.child(format(row.data())).show();
});
});
I am facing two problems with the jquery JS.
1 . (I have my default display length in the show '10' entries to be defaulted to 10). So for the first 10 records my logic works fine. When I click on next button and navigate to the remaining paginated records and click on any data row, my logic is not working.
<table>
<c: forEach items="${tdetails}" var="tdetail" varStatus="loop">
<tr>
<td>${loop.index+1}</td>
<td><a tag name="det12" id="delhi" href="#" >${tdetail.empNumber}</a></td>
<td>${tdetail.empName}</td>
<td>${tdetail.empDate}</td>
<td>${tdetail.empStatus}</td>
</tr>
</c:forEach>
</table>
<form id="employeeform" action="./getEmployeeStatusDisplay" method="get">
<input type="hidden" id="empNumber" name="empNumber" value="${tdetail.empNumber}">
</form>
2 . "Showing 1 to 10 of 100 entries" is not getting displayed. I am using the following code.
$(document).ready(function(){
$('#detailstable').dataTable({
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"bSortClasses": false,
"displayLength":10,
"oLanguage": {
"sInfo": "Showing START to END of TOTAL entries",
"sZeroRecords": "No data to show" },
"sDom": 'T<"clear">lfrtip'
});
$('td a[name="det12"]').click(function(){
alert("inside JS");
id=$(this).text();
alert(id);
$('#empNumber').val(id);
$.blockUI({
message: $('#spinnerbox'),
css: {
margin:'0px auto'
}
});
$("#spinner").show();
$("#employeeform").submit();
});
});
As you can see, when i click on the first column ${tdetail.empNumber} of the datatable which is href tag, it should invoke the 'det12' JS which results in displaying another form ('employeeform.jsp'). The problem is only for the first 10 datarows this logic is working fine, for the remaining 11 to 100 records this doesnt work.
It doesnt work because the <td> click function is resetted each time a new page is shown in the dataTable, and you only does $('td a[name="det12"]').click(function(){ once (thats why it works with the first page, rows 1-10). One way to solve this is by setting the trigger each time the datatable is redrawn (that is, when the user clicks on another page) the callback function fnDrawCallback can be used for that :
$('#detailstable').dataTable({
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"bSortClasses": false,
"displayLength":10,
"oLanguage": {
"sInfo": "Showing START to END of TOTAL entries",
"sZeroRecords": "No data to show"
},
"sDom": 'T<"clear">lfrtip',
fnDrawCallback : function() {
$('td a[name="det12"]').click(function(){
alert("inside JS");
id=$(this).text();
alert(id);
$('#empNumber').val(id); $.blockUI({ message: $('#spinnerbox'), css: { margin:'0px auto' } });
$("#spinner").show();
$("#employeeform").submit();
})
}
});
see demo -> http://jsfiddle.net/hf1zqpoz/ I cannot reproduce your setup entirely, but click through the pages, and click on records with the content "Trident".
It looks like some thread (which may have been previously invoked not destroyed properly) would have been creating these kind of problems. So i tried the following in the script tag of my JSP file. Then it is working fine. Hope this helps someone who is facing similar issue like this.
$('#detailstable').dataTable({
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"bSortClasses": false,
"displayLength":10,
});
var bindLinks = function(){
$('td a[name="det12"]').click(function(){
id=$(this).text();
$('#empNumber').val(id);
$("#employeeform").submit();
});
};
$("#detailstable").bind("draw.dt", function(){
bind();
});
});
Great forum. Thanks guys.
I want to add a row number for each row in my data table. I am using plugin from http://datatables.net The page which tells how to add the index is http://datatables.net/release-datatables/examples/api/counter_column.html
... however I don't know how to actually implement it to make it work. I know extremely little about jquery / javascript which would help in this case. I don't know where to put this code to make it work (if it helps i am also using Ruby on Rails)
The initialization code is:
jQuery ->
$('#staffs').dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
}
Here is an example from datatables.net site DataTables row numbers example
$(document).ready(function() {
$('#staffs').dataTable( {
sPaginationType: "full_numbers",
bJQueryUI: true,
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
},
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[ 1, 'asc' ]]
} );
} );
Regarding your SyntaxError: reserved word "function" on line 4 (in /home/ubuntu/ruby/scoreboard/app/assets/javascripts/staffs.js.coffee)' error
take a look at this rails, getting syntax error with coffee script
jquery is javascript. You need to add the code Daniel pasted between
<script language="javascript">
and
</script>
tags.
I am working with latest dataTable 1.10 and gem rails datatable and ajx
for
finding the DataTable row number(Serial Number)
def data
outer = []
records.each_with_index do |record, index|
outer << [
# comma separated list of the values for each cell of a table row
# example: record.attribute,
index + 1 + params[:start].to_i,
record.company_name,
record.id,
record.patients.count,
record.revenue_total
]
end
outer
end