Javascript newbie question
I'm fetching user input from text and use that value to send to the controller for further process. On page init everything is fine, now I want to bind OK button to send users value to my page init script (I'm trying to avoid copying script). Here's the code
#Html.ActionLink("OK", "Ajax", null, new { #class = "button", #id ="myDate" })
on page init
$(document).ready(function dataTable() {
$('#dataTable').dataTable({
"bServerSide": true,
"fnServerParams": function (aoData) {
var date = $('input[name="myDate"]').val();
aoData.push({ "name": "Date", "value": date });
});
});
on user input and clicking the button I should take that input and sent to the above script to process
$('#myDate').click(function () {
var date = $('input[name="myDate"]').val();
// ????
// Should I change first function to receive parameter as argument
});
One way is to factor out the code to get the date outside the datatable init
function getDate(){
var date = $('input[name="myDate"]').val();
return date;
}
Then in your datatable init
var date = getDate();
and the same in your click event
$('#myDate').click(function () {
var date = getDate();
});
You should end up with this
$(document).ready(function dataTable() {
function getDate(){
var date = $('input[name="myDate"]').val();
return date;
}
$('#dataTable').dataTable({
"bServerSide": true,
"fnServerParams": function (aoData) {
var date = getDate();
aoData.push({ "name": "Date", "value": date });
});
});
$('#myDate').click(function () {
var date = getDate();
});
});
Related
I'm filtering my calendar, I change the start and end date, status of my events, and other stuffs. I do that with:
$("body").on("click", "#btnFiltrar", function() {
fechaIni = $("#fechaIni").val();
fechaFin = $("#fechaFin").val();
cp = $("#txtCP").val();
var events = {
url: "./php/xxxxxxxx.php",
type: "POST",
data: {
fechaIni: fechaIni,
fechaFin: fechaFin,
cp: cp,
provincia: provincia,
...
}
}
$("#calendar").fullCalendar("removeEventSource", events);
$("#calendar").fullCalendar("addEventSource", events);
$("#calendar").fullCalendar("refetchEvents");
});
It works fine. But when I want to change the variable hiddenDays dynamically, I can't make it work!
I add to my code this:
(By default this variables are global)
var dias = ["0","1","2","3","4","5","6"];
var ocultarDias = []; // is empty because it shows all days
// inside click button
diasSeleccionados = $("#selDias").val(); // returns array eg: ["1","2","3","4","5"]
ocultarDias = $(dias).not(diasSeleccionados).get(); // compare 2 arrays and get the difference
So, with that and the call fullcalendar with the attribute:
function llenarCalendario() {
$("#calendar").fullCalendar({
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}
I miss something? I want to do this without reload the page, just call again the function or, as the function on click button, refetchEvents or something like that. Is possible?
You can recreate the calendar and add the events, which you have already have, again with the following method.
function reloadCalendar(){
//Get all events in a array
var events = $("#calendar").fullCalendar( 'getEventSources' );
$("#calendar").fullCalendar( 'destroy' ); // Destroy the calendar
$("#calendar").fullCalendar({ //Recreate the calendar with the hidden days
hiddenDays: [ 2, 4 ]
});
//With JavaScript
events.forEach(function(event) { //Restore all events
$("#calendar").fullCalendar( 'addEventSource', event);
});
//With jQuery
var jEvents = $.makeArray(events);
$(jEvents).each(function( i ) {
$("#calendar").fullCalendar( 'addEventSource', events[i]);
});
}
Now you simply can call the method. I hope it was helpful.
var newhiddendays = [0, 6]; // show Mon-Fr (hide Sat/Sun)
$('#calendar').fullCalendar('option', 'hiddenDays', newhiddendays);
You have to use it with optionmethod in order to set new options for your calendar
https://fullcalendar.io/docs/utilities/dynamic_options/
function llenarCalendario() {
$("#calendar").fullCalendar('option',{
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}
I finally found a way to do that without reload the page. With the help of #todes using 'options' and adding the three lines below that.
Very important: the array of hiddenDays must be an array of ints.
var dias = ["0","1","2","3","4","5","6"];
var ocultarDias = []; // is empty because it shows all days
$(document).ready(function () {
llenarCalendario();
$("body").on("click", "#btnFiltrar", function() {
fechaIni = $("#fechaIni").val();
fechaFin = $("#fechaFin").val();
cp = $("#txtCP").val();
var diasSeleccionados = $("#selDias").val(); // select multiple, returns array eg: ["1","2","3","4","5"]
ocultarDias = $(dias).not(diasSeleccionados).get(); // compare 2 arrays and get the difference
ocultarDias = ocultarDias.map(Number); // array of strings to int for fullcalendar to work
var events = {
url: "./php/xxxxxxxxxx.php",
type: "POST",
data: {
fechaIni: fechaIni,
fechaFin: fechaFin,
cp: cp
}
}
$("#calendar").fullCalendar('option', {
hiddenDays: ocultarDias
});
$("#calendar").fullCalendar("removeEventSource", events);
$("#calendar").fullCalendar("addEventSource", events);
$("#calendar").fullCalendar("refetchEvents");
});
});
function llenarCalendario() {
$("#calendar").fullCalendar({
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}
So, adding on to my question from yesterday: jQuery AJAX call function on timeout
Using the first answer from the post from yesterday, the table does indeed reload without refreshing the whole page. It does so after 30 seconds.
But my problem lies before the first refresh...
The page loads, and the records are duplicated. But after the first refresh and every refresh after (unless I manually refresh using F5), everything is fine. No duplicates.
I'm trying to figure out why there are duplicates and how to remove the duplicates upon the page's initial ready event.
Here is the code, starting with the ready event:
$(document).ready(function()
{
$.ajax({
url:'api/qnams_all.php',
type:"GET",
dataType:"json"
}).done(function(response) {
console.log(response.data);
renderDataTable(response.data)
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
});
Here is the function to load the DataTable:
function renderDataTable(data)
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true
});
// then I add the reload function
setInterval( function () {
$dataTable.ajax.reload();
}, 30000 );
});
As stated above, the setInterval function works like how it should. It's just the initial page load is duplicating all of the records.
Does anyone see why and how to fix it?
I think you've got some duplication going on. You don't need to load the ajax flie and then load it again when you set up the DataTable.
Try replacing all of your code with this:
$(document).ready(function() {
// load and render the data
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true,
// the init function is called when the data table has finished loading/drawing
"init": function() {
// now that the initial data has loaded we can start the timer to do the refresh
setInterval(function() {
$dataTable.ajax.reload();
}, 30000);
}
});
});
Calling clear prevents duplicate rows while loading data into table:
$("#checkResourcesButton").click(function() {
$.post("./get/resources", {
featureName: $('#myvar').val()
}).done(function (data) {
var table = $('#table-output').DataTable();
table.clear();
var json = JSON.parse(data);
for (var row in json) {
var nameVal = json[row].Name;
var emailVal = json[row].emailId;
var roleVal = json[row].role;
var startDateVal = json[row].startDate;
var endDateVal = json[row].endDate;
var toAdd =
{
name: String(nameVal),
emailId: String(emailVal),
role: String(roleVal),
startDate: String(startDateVal),
endDate: String(endDateVal)
};
table.row.add(toAdd);
}
table.draw();
});
});
I have a website with a DataTable. Following this I create a js event on clicking on a row. The event stores an id corresponding to the clicked row in a variable and following this I posted a message to the shiny-iframe.
$(document).ready(function() {
var table = $('#example').DataTable( {
"columnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
}
]
});
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
var table_row_id = data[0];
var frame = document.getElementById('shiny-iframe');
frame.contentWindow.postMessage(table_row_id, '*');
} );
} );
Still I am not sure how to proceed from here. The end result is to have shiny reloading the app in the iframe with as argument the variable stored in table_row_id.
In this fiddle inside the view appointments tab,there is add timing button.When I click on the button then a new row gets added.Now when I click on the calender icon then a pop comes up which shows the current hour and minutes.But I want it to show 00:00. Can any body please tell me how to do?
I have tried to modify the setDate method inside the bootstrap date time picker source code
setLocalDate: function (localDate) {
if (!localDate)
this.setValue(null);
else
this.setValue(Date.UTC(localDate.getFullYear(), localDate.getMonth(), localDate.getDate(), localDate.getHours(), localDate.getMinutes(), localDate.getSeconds(), localDate.getMilliseconds()))
},
to
setLocalDate: function (localDate) {
if (!localDate)
this.setValue(null);
else
this.setValue(00, 00, 00, 00,00, 00, 00))
},
but it did not work.Please anybody tell me what else do I have to change
As #RobG already said, you can simply set the value in the initialization routine
ko.bindingHandlers.datepicker1 = {
init: function (element, valueAccessor, allBindingsAccessor) {
$(function () {
$(element).parent().datetimepicker({
pickDate: false,
pickSeconds: false,
minuteStep: 10
});
$(element).parent().datetimepicker('setValue', '00:00');
});
// ...
See updated JSFiddle
Update:
If you want 00:00 as default value only, you must pick the value from the valueAccessor first and set 00:00, if the value is undefined
init: function (element, valueAccessor, allBindingsAccessor) {
$(function () {
$(element).parent().datetimepicker({
pickDate: false,
pickSeconds: false,
minuteStep: 10
});
var accessor = valueAccessor();
var val = ko.unwrap(accessor) || '00:00';
$(element).parent().datetimepicker('setValue', val);
});
// ...
See JSFiddle
Update:
Unfortunately, I cannot find any documentation about version 2.2.0.
Testing, if the accessor is a function, seems to work
var val = valueAccessor();
if (typeof(val) == 'function')
val = val();
$(element).parent().datetimepicker('setValue', val || '00:00');
Updated JSFiddle
I've a function that is triggered from a on click event. It's open up my popup, and im woundering how to send my date to my 'popupbeforeposition'.
module.selectedDay = function($this) {
var date = $this.data('date');
$('#popupWorkSelect').popup('open');
};
$('#popupWorkSelect').on({
popupbeforeposition: function (event) {
//Get date sended to this function?
console.log(event);
},
popupafterclose: function(event) {
}
});
I know that I can work with my 'module.selectedDay' function like this but it's not the way I want to do it.
module.selectedDay = function($this) {
var date = $this.data('date');
$('#popupWorkSelect').find('#myElement').innerHTML = date;
$('#popupWorkSelect').popup('open');
};
When the click happens, store the value in data of the popup.
$popup.data("mydata", date);
in the popupbeforeposition event, take it out from data and use it. (Here the context would be within the popup so data you need would lie in $(this). So the way of access would be this:
$this.data("mydata")
Demo : http://jsfiddle.net/hungerpain/LV9VW/3/
PS assume $popup and $this are the popup elements