jquery datepicker onselect not firing - asp.net

I have 2 input boxes for inputing start date and end date.I need to verify that the start date is earlier than the end date.I have the following code to verify that but the code doesn't seem to be firing when I attach to the onselect event of the datepicker control.Can someone please tell what I'm doing wrong?
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".date").datepicker({
onSelect:function(dateText,inst){
var startDate=new Date($("#_createDateFromInput").val());
var endDate=new Date($("#_createDateToInput").val());
if(startDate!=""&&endDate!="")
{
if(startDate>endDate)
{
alert("End date cannot be earlier than start date");
}
}
}
});});
</script>
thanks!!
The markup for the above is(this is in asp.net):
<label>Date From</label>
<input class="date" runat="server" id="_createDateFromInput" />
<label id="to">To</label>
<input class="date" runat="server" id="_createDateToInput" />
El Ronnoco had I believe has latched onto something...I notice when I remove the runat="server" tag I am able to fire the even...however now I am faced with another
issue to retrieve the value during post back(i.e when user finally submits)..any one have an idea?

A simpler way to achieve this is to prevent that the user can select an earlier date for the endDate.
This can be simply done by using the minDate option of Datepicker plugin
$("#startDate").datepicker({
onSelect:function(dateText,inst){
$( "#endDate" ).datepicker( "option", "minDate", new Date(dateText) );
}
});

I use this code, from the jQuery UI example page: http://jqueryui.com/demos/datepicker/#event-search
Basically it takes 2 inputs, makes them datepickers then onselect limits both the mindate and max date. It's a very clever piece of code.
$(function() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" );
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});

thanks guys for all your input.I used a lot of what you had written down.I was able to make that work for some reason having the attribute runat="server" causes all kinds of problems for jquery.I had to remove the tag and access it using the request object that is inherent in the page.For those interested in the syntax:
request.form["startDate"].tostring();
where startdate is the attribute name value for that field.

Related

Having onchange event fire when input value set from data

I've been looking at many two-way data binding libraries and so far haven't found one that will fire onchange events when the input's value is set from a change on the model. Is there any way to do that with ractive.js?
It's possible, but is a little bit hacky. Browsers only fire the change event as a result of user interaction (rather than input.value = 'someNewValue'), so you have to watch the model and fire the event yourself:
var ractive = new Ractive({
el: 'main',
template: '#template',
data: { name: 'world' },
twoway: false
});
ractive.observe( 'name', function () {
// name has changed, need to simulate an event
var event = new Event( 'change' );
ractive.find( 'input' ).dispatchEvent( event );
});
ractive.find( 'input' ).addEventListener( 'change', function ( event ) {
console.log( 'event was fired', event );
});
// check the console!
ractive.set( 'name', 'everybody' );
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<main></main>
<script id='template' type='text/ractive'>
<h1>Hello {{name}}!</h1>
<input value='{{name}}'/>
</script>
Note that twoway binding has been disabled, otherwise you'd get extra events firing all over the place when the user did interact with the input - so you would need to listen for input/change events and handle those interactions yourself.
The answer (for my purposes) is actually quite simple. First a little background - which I probably should have outlined in the original question. Let's say you're viewing/editing a customer profile. Meanwhile someone else is doing the same. They update a phone# and resave the profile. Without anything special being done you aren't going to see that new phone# unless you reload the profile. My goal is to make our data/forms 'reactive'. One of the difficulties was updating a form. In itself that's easy enough but how to handle any onchange events on inputs. Let's say a country is changed so a new list of regions needs to appear. Me changing the country would fire off the country's onchange event and a new list would appear. If a reactive change occurred and updated the country the onchange wouldn't fire. That's a problem. To make a long story short, the answer is to not have any onchange events on inputs but have a Ractive.on('change') event and then parse the key path for anything of interest. That will catch changes from the human and changes from the 'beyond', either with set or merge.
var cust = {
firstname: 'Fred',
lastname: 'Flintstone'
}
ractive = new Ractive({
el: '#spot',
template: '#tmpl1',
data: {customer: cust},
lazy: true
})
ractive.on('change', function(kp) {
console.log(kp)
})
setTimeout(function() {
ractive.set('customer.firstname', 'Wilma')
}, 2000)
setTimeout(function() {
ractive.merge('customer', {firstname: 'Barney', lastname: 'Rubble'})
}, 4000)
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<body>
<div id='spot'></div>
<script id='tmpl1' type='text/tmpl'>
<input value={{customer.firstname}}>
<input value={{customer.lastname}}>
</script>
</body>

Contact form 7 Datepicker, date range between 2 dates

I would like to have two date field in my Wordpress contact form 7. A start-date and an end-date. The fields will be datepickers from the "Contact Form 7 Datepicker" plugin.
When visitor has selected a start-date he should only be able to select an end date that is 4 days later then the start-date.
How can I achieve this by only using the "contact form 7" form creator?
This is the syntax I put in the "contact form 7".
Start date charter*:
[date* date-start date-format:MM_d_yy]
End date charter*:
[date* date-end date-format:MM_d_yy]
And I added this code to the end of the functions file of the Wordpress theme.
function calendar_js(){
?>
<script>
jQuery(function($){
var start = $('.date-start input').first();
var end = $('.date-end input').first();
start.on('change', function() {
var start_date = $(this).datepicker('getDate');
start_date.setDate(start_date.getDate() + 3);
end.datepicker('option', 'minDate', start_date);
});
});
</script>
<?php
}
add_action('wp_footer', 'calendar_js');
Now the second date picker must be at least 4 days later then the first date picker.
May be this plugin will help you. This plugin works along with CF 7
http://wordpress.org/plugins/contact-form-7-datepicker/
And you can add your own javascript for date manipulation after adding datepicker in CF 7.
Example:
jQuery(document).ready(function($) {
$( ".from" ).datepicker({
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( ".to" ).datepicker({
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
2021 Update: Contact form 7 datepicker was removed from wordpress repository due to security reasons
https://blog.cf7skins.com/contact-form-7-datepicker-removed-security-vulnerability/
You can try the WP-Datepicker by Fahad Mahmood
This is my solution without the use of plugins,
this is the code of the CF7 fields:
Start date charter *:
[date* date-start]
End date charter *:
[date* date-end]
this is the code added in the functions.php file:
add_action('wp_footer', 'calendar_js');
function calendar_js()
{
?>
<script>
jQuery(function($)
{
var start = $('.date-start input').first();
var end = $('.date-end input').first();
start.datepicker ({dateFormat: 'yy-mm-dd', beforeShow: function() { $(this).datepicker('option','maxDate',end.datepicker('getDate')); } });
end.datepicker ({dateFormat: 'yy-mm-dd', beforeShow: function() { $(this).datepicker('option','minDate',start.datepicker('getDate')); } });
});
</script>
<?php
}
There is no way to achieve it with the form builder directly, but with a bit of JavaScript you can validate the second input field to get your desired behaviour.
Here is an example, that falls back to the earliest date possible once a date is selected, that is out of scope.
<input type=date class=c-date-start>
<input type=date class=c-date-end>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Add the below code to the page your form is located -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
jQuery(($) => {
const dateStart = $('.c-date-start')
const dateEnd = $('.c-date-end')
const minBuffer = 4
// Only allow dates in date end field that are after the date start field plus the minimum buffer
dateEnd.on('change', () => {
const startDate = dateStart.val()
const endDate = dateEnd.val()
if (startDate && endDate) {
const startDateMoment = moment(startDate)
const endDateMoment = moment(endDate)
const minDate = startDateMoment.clone().add(minBuffer, 'days')
if (endDateMoment.isBefore(minDate)) {
dateEnd.val(minDate.format('YYYY-MM-DD'))
}
}
})
})
</script>
On WordPress, you probably do not need to load jQuery extra and for the form markup you can add the classes in the CF7 builder like so:
[date date-427 class:c-date-start]
[date date-427 class:c-date-end]
Change the selectors and the minimum timespan according to your needs by adjusting the following declarations inside the source:
const dateStart = $('.c-date-start')
const dateEnd = $('.c-date-end')
const minBuffer = 4

How do I localize the validation messages in JQuery's Validation?

Is there a standard practice for localizing the JQuery Validation messages?
I've been able to hack something together by declaring my own ClassRules and referencing them instead of the default ones.
My code.
<input class="localized-required" id="myTextInput" name="myTextInput" type="text" value="" />
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
$.validator.addMethod("localized-required", $.validator.methods.required, '<%: Resources.Strings_ValidationMessages.SelectionRequired %>');
$.validator.addClassRules(
{
"localized-required": { "localized-required": true }
});
jQuery("#myForm").validate();
})
</script>
I'm just looking to see if there is a better way.
You could overwrite the messages object in the validator object.
$.validator.messages = {
required: '<%: Resources.Strings_ValidationMessages.SelectionRequired %>'
};
Or you could potentially use your own defaultMessage function.
$.validator.prototype.defaultMessage = function(element, method) {
var locale = magicFunctionToGetLocale();
var message = $.validator.localizedMessages[locale][method];
return this.findDefined(
this.customMessage( element.name, method ),
this.customMetaMessage( element, method ),
// title is never undefined, so handle empty string as undefined
!this.settings.ignoreTitle && element.title || undefined,
message,
"<strong>Warning: No message defined for " + element.name + "</strong>"
);
};
In the above example, $.validator.localizedMessages is an object created elsewhere in your code. The standard validation plugin does not have a localizedMessages object.
There are validation files available if you want:
https://github.com/jzaefferer/jquery-validation/tree/master/src/localization
Just get the ones you need and reference the .js file(s) in your page.
<script type="text/javascript" src="localization/messages_XX.js"></script>

jquery adding an onclick event to a href link

i am converting over from websforms to asp.net mvc and i have a question.
i have a loop that generates links dynamicallly where picNumberLink is a variable in a loop and image is a variable image link.
i want to avoid putting javascript actions inline so in my webforms project is did the following:
hyperLink.Attributes.Add("onclick", "javascript:void(viewer.show(" + picNumberlink + "))");
what is the equivalent using jquery in asp.net mvc?
I have seen examples of using the $(document).ready event to attach on clicks but i can't figure out the syntax to pass in the picNumberLink variable into the javascript function.
suggestions?
EDIT: If you generate your links with the ID of this form:
<a id="piclink_1" class="picLinks">...</a>
<a id="picLink_2" class="picLinks">...</a>
<script type="text/javascript">
$('a.picLinks').click(function () {
//split at the '_' and take the second offset
var picNumber = $(this).attr('id').split('_')[1];
viewer.show(picNumber);
});
</script>
var functionIWantToCall = function(){
var wrappedLink = $(this);
//some serious action
}
//this should be called on document ready
$("#myLinkId").click(functionIWantToCall);
If you need to get URL of picture, keep it in anchor`s href:
var functionIWantToCall = function(event){
event.preventDefault(); //this one is important
var link = $(this).attr('href');
//some serious action
}
$(document).ready(function()
{
$('#LinkID').click(function() {
viewer.show($(this).attr('picNumber'));
});
});
You can add an attribute called picNumber to your hyperlink tag and set this is your mvc view
The link in your view might look something like this:
<%= Html.ActionLink("Index", new { id = "LINKID", picNumber = 1 }) %>
Assuming you're able to change the HTML you output, can't you put the picNumberLink in the id or class attribute?
HTML:
<img src="..."/>
jQuery:
$(function() {
// using the id attribute:
$('.view').click(function() {
viewer.show(+/-(\d+)/.exec(this.id)[1]);
});
// or using the class attribute:
$('.view').click(function() {
viewer.show(+/(^|\s)foo-(\d+)(\s|$)/.exec(this.className)[2]);
});
}}

Cannot select grid element through jQuery

This is a follow-up question to ASP.NET How to pass container value as javascript argument
Darin Dimitrov has kindly provided his answer using jQuery,
But for some reason, I was not able to select the grid row I wanted to.
Here is the jQuery used to select row.
$(function() {
$('#_TrustGrid input[name^=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
Here is the actual output HTML markup.
<input
id="_TrustGrid_ctl16_ctl05_ctl00_trustDocIDTextBox"
type="text" value="198327493"
name="_TrustGrid$ctl16$ctl05$ctl00$trustDocIDTextBox"/>
I have just started using jQuery tonight and been going through the official jQuery Selectors documentation but have been unsuccessful.
Am I missing something here?
What I did to save the full id of the control I used in my .aspx page:
<input type="hidden"
id="SubcontractorDropDownID"
value="<%= SubcontractorDropDown.ClientID %>" />
You can then just get the value of the id and then use that in your query to know which row to use.
At first glance, I think you just want a '$' instead of '^' and you should be targeting the ID and not the NAME in your selector?
$(function() {
$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
I do not know why selecting through #_TrustGrid would not work.
I was able to get around the problem by specifying :input as shown below.
$(function() {
//$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(':input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});

Resources