Complicated jquery validation - javascript

I have a form that I want validated (using jquery validation plugin). Problem is that I need to do some pre-processing of form values before submitting for validation.
For example, one validation case is that the start time the user defines in the form cannot be before right now. I have 2 components that I need to get the values from in order to get the start time.
Here's how I currently capture that:
var mtgStart = new Date( startDate.getFullYear() + '-' + ( startDate.getMonth() + 1 ) + '-' + startDate.getDate() + ' ' + sTime );
I have read that I can pass these params (startTime) into the validation like this:
var defaults = jQuery.extend( validationPluginDefaults, {
ignore:'',
rules: {
meetingName:{
mtgNameRequired:true
},
e2: {
startTimeInPast:false
startTime:mtgStart
}
}
});
jQuery( "form[ id='mtg_form' ]" ).validate( defaults );
Question is, where do I create the "mtgStart" variable here?
And my validation method would look like this:
jQuery.validator.addMethod("lowerInt", function(value, element, params) {
var now = new Date();
var mtgStart = params[0]:
return now < mtgStart;
}
UPDATE:
I trigger the validation on click of the submit button now; no problem. Problem now is how do I pass arguments to the jquery validation plugin? I've tried using javascript arrays (as I've read), but I'm not able to access it. Here's my code:
jQuery.validator.addMethod( "createMtgInPast", function( val, el, params ){
var now = new Date();
var mtgStart = params[0];
var nowTime = now.getTime();
var setTime = mtgStart.getTime();
return nowTime < setTime;
}, "Cannot create meeting in the past." );
And here's my click handler for submit button:
$( '#submit_btn' ).click( function( data )
{
// Concatenate the start/end dates and their times.
var newStart = new Date( startDate.getFullYear() + '-' + ( startDate.getMonth() + 1 ) + '-' + startDate.getDate() + ' ' + sTime );
var newEnd = new Date( endDate.getFullYear() + '-' + ( endDate.getMonth() + 1 ) + '-' + endDate.getDate() + ' ' + eTime );
var defaults = jQuery.extend( validationPluginDefaults, {
rules: {
meetingName:{
mtgNameRequired:true
},
e2: {
createMtgInPast: true,
data:['TEST']
}
}
});
$( "#mtg_form" ).validate( defaults );

Got it, here's my updated code:
var defaults = jQuery.extend( validationPluginDefaults, {
rules: {
meetingName:{
mtgNameRequired:true
},
e2: {
createMtgInPast: [newStart]
}
}
});
I was creating a new method and passing the args there; wrong. Pass the args directly into the validation method.

Related

Laravel post request doesn't return correct data

My form is not updating the information when I manually change the textbox fields. When i get a confirmation email I get the wrong calculation in this example. When i process the information in my controllers it gets put correct in the database but incorrect in the email to my customer. even though it uses the same information.
$('#two-inputs').dateRangePicker(
{
separator : ' tot ',
startDate: '{{$start_date->start_date}}',
endDate: '{{$end_date->end_date}}',
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ disabled.indexOf(string) == -1 ]
},
getValue: function()
{
if ($('#date-range200').val() && $('#date-range201').val() )
return $('#date-range200').val() + ' to ' + $('#date-range201').val();
else
return '';
},
setValue: function(s,s1,s2)
{
var total = 0;
var temp_s1 = s1.split("-");
var temp_s2 = s2.split("-");
$('#date-range200').val(temp_s1[2] + "-" + temp_s1[1] + "-" + temp_s1[0]);
$('#date-range201').val(temp_s2[2] + "-" + temp_s2[1] + "-" + temp_s2[0]);
var start_date = s1;
var s1 = s1.split('-');
var s1 = new Date(s1[0], s1[1] - 1, s1[2]);
var s2 = s2.split('-');
var s2 = new Date(s2[0], s2[1] - 1, s2[2]);
//alert(datediff(s1, s2));
if(obj[$('#date-range200').val()] == null){
var prijs = {{$highest_price->name}};
} else {
var prijs = obj[$('#date-range200').val()];
}
var extra_kosten = {{$blog->schoonmaak}};
total += extra_kosten;
total += datediff(s1, s2)*prijs;
$("#aantal_nachten").val(datediff(s1, s2));
$("#prijs_per_nacht").val(prijs);
$("#totaal_prijs_nachten").val(total);
$("#prijs").html(prijs);
$("#nachten").html(datediff(s1, s2));
$("#prijs_nachten").html(datediff(s1, s2)*prijs);
$("#extra_kosten").html(extra_kosten);
$("#totaal_prijs").html(total);
//alert(start_date);
//alert(obj[$('#date-range200').val()]);
$("#prijstable").slideDown( "slow");
}
});
Screenshot of the input fields
Screenshot of what i get in the email i receive
Screenshot of how it shows in my database

Jquery Clone method increment name tag

Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}

jquery datatable data-order alternative

Is there any way to specify data-order attribute when setting the datatable's data dynamically?
For example this is what I used to have
<td class="sorting_1" data-order="1451599200000">1 Jan 2016</td>
Now I'm setting data through columnDefs
{
render: function (date) {
var d = new Date(date);
var parsedDate = d.getUTCDate() + ' ' + monthsAbbr[d.getUTCMonth()] + ', ' + d.getUTCHours() + ":" + d.getUTCMinutes();
return parsedDate;
},
targets: 4
}
So, I'm wondering if there's any API witch I can set the td's data-order atribute.
The render() function takes a few more arguments that should help you achieve your goal. Here's an example from the manual page on renderers:
{
data: 'created',
render: function ( data, type, row ) {
var dateSplit = data.split('-');
return type === "display" || type === "search" ?
dateSplit[1] +'-'+ dateSplit[2] +'-'+ dateSplit[0] :
data;
}
}
Applying this to your case, your render() function could be something like this:
render: function (data, type, row) {
if (type === "display" || type === "search") {
var d = new Date(data);
var parsedDate = d.getUTCDate() + ' ' + monthsAbbr[d.getUTCMonth()] + ', ' + d.getUTCHours() + ":" + d.getUTCMinutes();
return parsedDate;
}
return data;
}
See also the manual page on orthogonal data.

jQuery DatePicker background color for cells where event exists (on load)

I want to change the background-color for cells where events exist.
In this case for this day: 2016-04-07
I hope someone can help me, I don't find a solution here in SO.
Thank you
JS code:
// I WANT TO CHANGE BACKGROUND-COLOR FOR THIS DAY
var events = {"2016-04-07":[{"title":"Friday!!!!","description":"Weekend is starting!!!"}]};
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents
});
// Provide a function to find and display events
function findEvents (date) {
// Start by emptying our data container
$("#dateevents").empty();
// Potential date object
var dateObj = events[date];
// If no events exist for the selected date
if (!dateObj) {
return $("#dateevents").html( "<h2>" + date + ": No Events</h2>" );
}
// If we've made it this far, we have events!
$("#dateevents").html( "<h2>" + date + ": " + dateObj.length + " Events Planned</h2>" );
// Cycle over every event for this date
$.each(dateObj, function (index, event) {
// Build a list for each event
var $list = $("<ul>");
// Add all event details to list
$.each(event, function (name, desc) {
$("<li>").html(name + ": " + desc).appendTo($list);
});
// Place list in container
$list.appendTo("#dateevents");
});
}
Fiddle: http://jsfiddle.net/qSCek/6/
Try something like this, looping over the html you might want to put it in a function and call it on month change etc.
// Provide some event data in JSON format
var events = {"2016-04-07":[{"title":"Friday!!!!","description":"Weekend is starting!!!"}]};
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents,
});
$("td[data-handler='selectDay']").each(function(index,value){
var month = $(value).attr("data-month");
var year = $(value).attr("data-year");
var day = $(value).next().text();
var date = year+"-"+(parseInt(month) + 1)+"-"+day
$.each(events, function(i, v) {
var parts = i.split("-")
parts[1] = parts[1].replace("0","")
parts[2] = parts[2].replace("0","")
var i = parts[0]+"-"+parts[1]+"-"+parts[2]
if (i == date) {
console.log("hit")
console.log(date)
$(value).next().css("background","red")
}
});
})
// Provide a function to find and display events
function findEvents (date) {
// Start by emptying our data container
$("#dateevents").empty();
// Potential date object
var dateObj = events[date];
// If no events exist for the selected date
if (!dateObj) {
return $("#dateevents").html( "<h2>" + date + ": No Events</h2>" );
}
// If we've made it this far, we have events!
$("#dateevents").html( "<h2>" + date + ": " + dateObj.length + " Events Planned</h2>" );
// Cycle over every event for this date
$.each(dateObj, function (index, event) {
// Build a list for each event
var $list = $("<ul>");
// Add all event details to list
$.each(event, function (name, desc) {
$("<li>").html(name + ": " + desc).appendTo($list);
});
// Place list in container
$list.appendTo("#dateevents");
});
}
fiddle http://jsfiddle.net/qSCek/7/
Here is what I accomplished to do. The problem I think is that the onChangeMonthYear callback is called before the view is rendered. So I put a timeout to solve the problem.
// Setup our datepicker
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: findEvents,
onChangeMonthYear: function(year, month) {
setTimeout(changeBackground, 1, year, month)
}
});
var d = new Date();
changeBackground(d.getFullYear(), d.getMonth() + 1);
function changeBackground(year, month) {
for (var date in events) {
var d = new Date(date);
// if same day and year
if (d.getFullYear() === year && d.getMonth() + 1 === month) {
var day = d.getDate();
// retrieve all elements containing day
var elements = $('a:contains(' + day + ')');
elements.each(function(index) {
if ($(this).text() == day) {
$(this).css("background", "red");
}
});
};
}
}
And here is the fiddle

javascript change class doesn't perform the event

I am trying to make a ajax load of a table. I have 2 buttons "Free Cars", "Reservations". When click "Free Cars" load all info from database and on click of tr it redirects to an url.
$('.cars_table').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Then on click of "Reservations" I change the class of tbody :
$('#cars_table').removeClass('cars_table').addClass('res_made');
But it doesn't perform the script which
$('.res_made').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Instead it performs the first script and on click of reservations rows it goes to the .cars_table redirect url. With inspect element it shows that the class has changed but then it doesnt performs the script for that class. What is happening?
Event bindings happen on the DOM elements themselves. If you try to bind an event on all .res_made elements before there are any elements with this class, no events will be bound.
To solve your problem, you could bind your event once and check inside the handler which class is currently set.
You should dynamically bind the click events, because the class of the table can dynamically change. So to make it work in your case, you should change your javascript to the following:
$(document).on('click', '.cars_table tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
$(document).on('click', '.res_made tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
See this FIDDLE for an example. Of course, as an alternative, you could also bind the event once and check for the class of the table in the event handler, like Martin Denk suggested.

Categories

Resources