jEditable - How to bypass the submit in datepicker onselect event - javascript

I am using jeditable with datepicker and i wish to do some validation once user select a date before submit it to the database. I gone through the jeditable-datepicker.js and realized that the submission is triggered once onselect event happened. How can I include conditions in the event so invalid date wont be submitted to the database?
Here is my trial by using the onsubmit event:
$('.expirydatepicker').editable('#(Url.Action("Edit", "Stock"))',
{
type: 'datepicker',
indicator: 'saving...',
event: 'dblclick',
tooltip: 'Double click to edit...',
style: 'inherit',
width: ($('.datepicker').width() - 10) + "px",
onsubmit: function (settings, td) {
var tid = $(td).attr('id');
//alert(tid);
$.ajax({
async: false,
url: '/Stock/CompareDate',
type: 'GET',
data: { id: tid },
success: function (result) {
if (result < 0) {
alert("Expiry dare cannot be earlier than storage date");
return onSelect(false);
}
else {
return true;
}
}
});
}
});
the jEditable-datepicker function :
/* attach jquery.ui.datepicker to the input element */
plugin: function( settings, original ) {
var form = this,
input = form.find( "input" );
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
dateFormat: 'D, dd M yy',
onSelect: function() {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
I wish to know is there anyway I can either "stop" the onselect event if the input is invalid??
Hope can get some help here... thanks....

try something like this:
plugin : function(settings, original) {
..
$(this).find('input').datepicker().bind('click', function(e) {
//e.preventDefault() // also test this
return false;
})

Can you simply check whether the selected date is valid, and only submit and form if it is?
onSelect: function(dateText, inst) {
if (/* dateText is valid */) {
form.submit();
}
}

i get it done by not stopping the submission, but change the input value back to default value if validation failed. This is the only way I could get it done. Thanks!

Related

Add datepicker to filter data in Datatable

I would like to add a datepicker to filter data in a Datatable.
I saw many example where the datepicker is used with a range of dates, but I would like that the Datatable shows only the data which contain the date selected in the datepicker.
I've tried to do it here: https://jsfiddle.net/c9q5b0k3/3/
The javascript code I've wrote is:
$(document).ready(function() {
$('.datepicker').datepicker({
format: "yyyy/mm/dd"
});
});
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
var dateSelected = $('#date').val();
var date = data[4];
if (dateSelected === "") {
return true;
}
if (date === dateSelected) {
return true;
}
return false;
}
);
$(document).ready(function() {
var table = $('#sspTable').DataTable({
responsive: true
});
$('#date').keyup(function() {
table.draw();
});
});
But the problem that it only works if I select a date in the datepicker and then I click the arrows in the Datatables(the ones that order the data) or if I press multiple times Enter.
What is the problem? Is it possible otherwise to add the datepicker to the search bar of the Datatable?
Thanks in advance!
You need to call table.draw() when a value is selected in the datepicker. To do that you can amend the existing keyup event handler you have to also include change, like this:
$('#date').on('keyup change', function() {
table.draw();
});
Updated fiddle

Bootstrap Datepicker on change firing 3 times

Hi I have been trying to just get the date of a bootstrap date picker and have been able to but it seems to fires 3 times. NOTE: This is not jquery date picker but bootstrap date picker.
Using this date picker: https://github.com/eternicode/bootstrap-datepicker, not older eyecon.ro one.
$(".date-picker").on("change", function(e) {
contents = $(this).val();
id = $(this).attr('id');
console.log("onchange contents: " + contents);
console.log("onchange id: " + id);
});
HTML:
<input id="start_date" type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" />
I have used a few other options other than change, like
$('.date-picker').datepicker().change(function(){};
But this does not close date picker, hoping there is an easy solution to this. thx
You should be using the "changeDate" event. For example:
var datePicker = $('.date-picker').datePicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
Please view the documentation here for more info on this event.
it does not fix the problem, but i was using the datepicker to send through an ajax post, so the 3 change events was causing me problems - the 3rd event always failed. even if the documentation says to use a changeDate event, it doesn't seem right to me to fire the input tag's change event 3 times. the value isn't changing 3 times!
I wrote a simple 'debounce' function to get around the problem. doesn't fix the issue - which is due to multiple change events being fired from the methods: setValue (line 508) _setDate:(line 1048) and setValue (line 508) (version 1.3.0) of the widget.
var lastJQueryTS = 0 ;// this is a global variable.
....
// in the change event handler...
var send = true;
if (typeof(event) == 'object'){
if (event.timeStamp - lastJQueryTS < 300){
send = false;
}
lastJQueryTS = event.timeStamp;
}
if (send){
post_values(this);
}
it is pretty simple, just finds the jquery 'event', and makes sure that values in a window of 300ms are ignored. in my testing this all happened in 30 msec or so.
As some has mentioned already, use this:
$('#calendar').on("changeDate", function() {
});
The trick is to use changeDate instead of change.
It seems as if when checking the change event, if the change was from actual user interaction, the change event contains a value for originalEvent.
The event does NOT contain this value if the input was changed via JS:
$obj.val('1990-03-07').change() and the same with bootstrap-datepicker
Here's how I set it up:
Generic initial setup
// General selector for date inputs
var $obj = $('input[type="date"]');
$obj.datepicker({
// options here, not important for this example
});
Handle bootstrap-datepicker specific changes
$obj.datepicker().on('changeDate', function (event) {
handleInputDateAndTimeChange(event);
});
Now, deal with user interaction changes
$('input[type="date"], input[type="time"]').change(function (event) {
// This checks if change was initiated by user input and NOT JS
if(event.originalEvent !== undefined) {
handleInputDateAndTimeChange(event);
}
});
And finally, here's the handleInputDateAndTimeChange function
function handleInputDateAndTimeChange(event) {
var $input = $(event.target);
// Do what you want with $input object here...
}
I tried the answer from #pgee70 and it doesn't work for me. So this is my solution, hope its help
var send=true;
$('.input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
language: 'es-ES',
weekStart: 1,
format: 'dd/mm/yyyy',
enableOnReadonly:false,
calendarWeeks: true,
autoclose: true,
todayHighlight:true
}).on("changeDate", function(e) {
if(send){
modificarFechaAplicacionCliente($("#input_filtro_fecha_cliente").val());
send=false;
}
setTimeout(function(){send=true;},200);
});
It´s not a beaty solution, but it´s work.
Similar to the above answer, but you should use datepicker unless you've renamed the function:
var datePicker = $('.date-picker').datepicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
This works for me, except in my case, I renamed the function to datepickerBootstrap to avoid the clash with JQuery's. So then it would become:
var datePicker = $('.date-picker').datepickerBootstrap().on('changeDate', function(ev) {
// On change functionality
});
It is fixed find your fixed js datepicker file HERE
Read fixing description HERE
I have faced the same problem with bootstrap-datepicker when it used with the jQuery OnChange event they call function 3 times. Here is my code
#Html.TextBoxFor(x => x.CmpStartDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "Start date" })
#Html.TextBoxFor(x => x.CmpEndDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "End date" })
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
console.log("Call search method");
}
</script>
We need to call this function only one time, Not multiple time so you can use the below logic to fix this problem
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
var i = 0;
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
i++;
console.log(i);
if (i == 3) {
SearchThisDateRecords(cmpStartDate,cmpEndDate);
}
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
i =0; //Reset i value
console.log("Call search method");
}
</script>
Get global variable count and check if equal to 0 then execute Your function.
var count=0;
$( "#Id" ).datepicker({ minDate: 0}).on('change',function (){
if(count==0)
validity();//any function
count=1;
});
validity(){ count=0;}
bit annoying..
my code was:
var c=0;var send=false;
$(document).ready(function() {
jQuery( ".ed" ).datepicker({
format: "yyyy-mm-dd",
autoclose:!0
}).on('change',function() {
if(c==2){
c=0;
send=true;
}else{
c++;
send=false;
}
});
});
Please use changeDate function in place of change .
var LastController =['id','value']; //global variable...
function datepeakerchange(e){
if ((LastController[0] != e.target.id && LastController[1] != e.target.value) || (LastController[0] == e.target.id && LastController[1] != e.target.value)) {
LastController[0] = e.target.id;
LastController[1] = e.target.value;
write your code....
}
}
var pickerFireCount = 0;
function checkSelectedDateIsHollyday(rId) {
pickerFireCount++;
if (pickerFireCount == 3) {
if (!selectedDateIsHolyday(rId)) {
showInfoMessage('The date you selected is a holiday.');
pickerFireCount = 0;
}
}
}

How to destroy jQuery validation and any further attempts at submission?

I have the following code for the jQuery validation plugin.... basically on submit, I slide everything up & fade it out... the only problem is, if you're quick enough, you can submit the form multiple times. How can I make sure that any presses of the enter key on the input (or clicks on that submit button) will not submit further?
Basically what happens, is that the form will load up the url in the action attribute when no javascript is there, so purely unbinding doesn't work... (even if it did, I can always press enter / click fast enough to get it to do a couple more....)
jQuery('.desired').validate({
debug: true,
rules: {
email: {
required: true,
email: true
}
},
wrapper: "div",
messages: {
email: "Please enter a valid email address."
},
errorPlacement: function(error, element) {
error.hide().appendTo(element.parent()).hide().slideDown();
},
errorClass: 'help-text',
submitHandler: function(form) {
var $ = jQuery;
var url = $(form).attr('action');
var query = $(form).serialize();
$.ajax({
url: url,
type: "POST",
data: query,
success: function() {
$("<p class='help-jquery'><b>Thanks</b>")
.insertAfter(jQuery(form))
.css('height', function(i,h) {
$(this).hide()
return h;
});
// $(form).css('height', $(form).height());
$(form).slideUp('slow');
$(form).fadeOut({ queue: false, duration: 'slow' });
// $('.help-jquery').fadeIn('slow');
$('.help-jquery')
.css('opacity', 0)
.slideDown('fast')
.animate(
{ opacity: 1 },
{ queue: false, duration: 'slow' }
);
//$('.desired submit').click(function(){
//return false;
//});
},
error: function() {
console.log('Error: did not submit properly');
},
complete: function(e) {
//$('.desired').unbind('submit');
//e.preventDefault();
//return false;
}
});
},
success: function(error,element){
},
highlight: function(error){
// This empty function needs to be here for this to work
}
});
You're on the right track with unbind(), it solves half of your problem because it will effectively suppress validation on form submission.
To solve the second half, you only have to neuter the form's submit event after unbinding, by registering the appropriate handler:
$(form).unbind("submit").submit(function() {
return false;
});
Use a boolean variable, like this:
var didValidate = false;
if(!didValidate) {
jQuery('.desired').validate({
//... your code here
});
}
In your AJAX success function, set didValidate to true.
Have a variable that is 1 or 0. before you do any validation, check that the variable is equal to 0. If it isn't 0, do nothing. If it is, continue. Once the validation passes, set the variable to 1 so that the validation cannot occur again.
Use event namespaces:
The name following the '.' let's you target handlers more specifically.
This at the top of the submit handler:
$(form).bind('submit.temp_submit_hold', function(e){
e.preventDefault();
e.stopPropagation(); //added this in case the plugin's handler func uses bubbling
return false;
} );
This at the top of the complete callback for the ajax call:
$('.desired').unbind('submit.temp_submit_hold');
A little more explanation after seeing your comments in complete. The time to preventDefault is immediately after your onsubmit handler starts working. On complete is when you want to enable it again. So we bind a func that stops it with prevent default and then unbind it to toggle behavior. I also added stopPropagation in case the plugin uses delegation/bubbling.
Probably the simplest is to add something like this to your submithandler
submitHandler: function(form) {
var $ = jQuery;
if ( $.data(form, "submit") ) > "" return false;
$.data(form, "submit", "in progress");
// .. the rest of your handler
}
If you want to allow the form to submitted again later, remove the .data() on success.
Use the .destroy() method.
This question and its answers are quite old. So since that time, the developer has added a .destroy() method to detach the validation plugin from the form.
Destroys this instance of validator freeing up resources and unregistering events.
// Initialize the validation plugin on your form
var validator = $("#myform").validate();
// Remove validation from your form
validator.destroy();
// After this point `#myform` is back to its original state without validation.
https://jqueryvalidation.org/Validator.destroy/
To stop multiple submissions, disable the submit button within the plugin's submitHandler function. (The submitHandler only fires when the form is valid and you've already clicked the submit button.)
submitHandler: function(form) {
// validation & submit success, so disable submit button
$("#yourSubmitButton").prop('disabled', true);
// your ajax code here
return false;
}

Jquery autosuggest

I am new to jquery.
I am using the below code for showing autosuggest in text box.
$().ready(function() {
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
//$("#suggest1").autocomplete(cities);
$("#custName").autocomplete(arrNames, {
multiple: false,
minChars: 0,
width: 190,
matchContains: true,
autoFill: false,
mustMatch: true,
max: 20,
}
});
});
My problem is I want to call a javascript function along with the index of arrNames as parameter when user select one name from autosuggest. Please help me.
Here is how you do it (using jQuery ui autocomplete) :
$("#custName").autocomplete(
source: arrNames,
select: function (event, ui) {
//Do stuff here
}
}
From jqueryUI website :
Select
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
EDIT :
It seems you are using Autocomplete plugin from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
This plugin is deprecated... You should use jQuery ui autocomplete : http://jqueryui.com/demos/autocomplete/

Finalizing editing in jqgrid

I using jqgrid with great succes in the following way:
The data is loaded from the server as JSON
The user do inline editing
When a save-button is clicked all the data is serialized using:
var data = $("#mygrid").getRowData();
var datajson = JSON.stringify(data);
The problem with this aproach is that I will get the input elements in my json-data if the user has not pressed return or moved away from the edited cell. Is there any way to end edit mode i jqgrid?
You can use saveRow to save the data.
To use saveRow you have to know the row id of the current editable row. You can for example save the rowid of the current editing in a variable (before you call editRow) and use the value for calling of the saveRow method.
UPDATED: see the demo. First select some row, modify the values and then click on the "Save current editing row" button. You will see that the changes will be saves.
I have solved it by triggering "keydown" ENTER event on element:
editoptions: {
dataInit: function(elem) {
$(elem).datetimepicker({
dateFormat: "yy-mm-dd",
onClose: function(datetimeText, datepickerInstance) {
$(elem).trigger($.Event( "keydown", { keyCode: $.ui.keyCode.ENTER } ))
}
});
}
}
I use remote submit for each cell, and as I used "contenteditable" div for cell editor (for multiline text), i wanted to finish cell editing with ctrl-enter.
( Based on Oleg's answer and How to close cell-editor? and http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing )
$(document).ready(function() {
var grid,currentCell;
$(".jqGrid_wrapper").on("keydown","div[contenteditable]",function (e) {
if (e.ctrlKey && e.keyCode == 13)
{
grid.jqGrid("saveCell",currentCell.iRow,currentCell.iCol);
return false;
}
return true;
});
grid=$("#table_list_2");
grid.jqGrid({
url: ...
cellEdit: true,
cellsubmit: 'remote',
cellurl: '..',
beforeEditCell: function(rowid, cellname, value, iRow, iCol) {
currentCell={
rowid:rowid, cellname:cellname, value:value, iRow:iRow, iCol:iCol
}
}
});
});

Categories