jQuery finding descendant by ID not working - javascript

I'm trying to change the value of a jQuery datepicker input element in a form to the first date in the week of the user-selected date once the submit button is clicked but before the form is actually submitted.
I'm finding that the following Javascript works (using a class selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find('.week-picker').datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
startDate is a Date object.
But this code does not work (using an ID selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find("#week-picker").datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
console.log($(this).closest('form').find(".week-picker").datepicker( "setDate", startDate ).val()); produces a proper date, like 06/27/2018.
console.log($(this).closest( 'form' ).find('#week-picker').val()); produces undefined.
Why is this happening? Isn't an ID a valid selector?
HTML:
<form action="/checkin" method="post">
<div class="form-group row mb-2">
<div class="col-md-6 offset-md-3">
<input class="week-picker form-control" type="text" id="week-picker" name="week_start" placeholder="Select week" style="opacity: 0;position: absolute;">
</div>
</div>
<div class="form-group row mt-4">
<div class="col">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
The datepicker portion of my JS:
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$(this).closest( 'form' ).find('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$(this).closest( 'form' ).find('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$(document).on( 'mousemove','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').addClass('ui-state-hover'); });
$(document).on('mouseleave','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').removeClass('ui-state-hover'); });

#week-picker is a valid selector, as long as your input has that ID assigned. What is happening in your case is that there is JS turning your input into a datepicker, and it changes the ID of the element when it loads. As you posted from your element inspector, your input no longer has the week-picker ID, it is now dp1529862475978.
This is not uncommon, and the behavior you're getting is the expected one. If you need to make sure that you're targeting this datepicker instead of another one with the same class, you can use the name attribute:
$("input[name='week_starting']")
You should never have 2 inputs with the same name on the same page, so it's as unique as an ID. The ID you're seeing in the element inspector is probably randomly generated, so you don't want to use that.

Related

Datepicker ui - check if dates from/to overlapping disabled days

I have 2 datepickers - date from and date to, something like hotel reservation system. How do I check (and show hidden div.error) if there are some disabled days in selected period?
Ex. - selected dates - from 2021-12-20 to 2021-12-31; disabled days are ["2021-12-25", "2021-12-26"] -> show "error".
<div class="error" style="display:none">Sorry, but we have no available rooms in selected dates.</div>
<script>
$( function() {
var disableddates = ["2021-12-25", "2021-12-26"];
$.datepicker.setDefaults($.datepicker.regional["de"]);
$( "#from" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [ disableddates.indexOf(string) == -1 ]
}
});
$( "#to" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [disableddates.indexOf(string) == -1 ]
}
});
});
</script>

Bootstrap Month-Year Picker [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to add a couple of month-year pickers to a form that I'm creating in a Bootstrap template. I have found a plugin to do exactly what I need, however it was written in an older version of jQuery and therefore breaks... I can't roll back to a previous version as it will break other plugins on the page.
What I need is here: http://techbrij.com/month-range-picker-jquery-ui-datepicker
It's a simple way to enter a date range using only month/year options. It will be used to select periods of employment. Can anyone steer me in the right direction to migrate this to jQuery 2.1.*?
EDIT 2016-02-08
It seems that the conflict lies with my bootstrap template. The template I'm using is AdminLTE by Almsaeed Studio
This is what gets rendered after following all the steps to load jquery/jquery-ui
It appears to work fine, I reconstructed an example using the following script url's for Jquery(version 2.1.3) and JqueryUI(version 1.11.2). Make your you are including both in a script tag right before your closing </body> tag. The original code is from an online article at http://techbrij.com/month-range-picker-jquery-ui-datepicker.
cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js
cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js
Live Example: http://codepen.io/larryjoelane/pen/jWeVPE
HTML:
<div style="text-align:center;">
<label for="from">From</label>
<input type="text" id="from" name="from" readonly="readonly" />
<label for="to">to</label>
<input type="text" id="to" name="to" readonly="readonly" />
<input type="button" id="btnShow" value="Show" />
</div>
CSS:
.ui-datepicker-calendar {
display: none;
/*use the line below instead to override existing css*/
/*display:none !important*/
}
JavaScript:
$("#from, #to").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
},
beforeShow: function(input, inst) {
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length - 4, datestr.length);
month = jQuery.inArray(datestr.substring(0, datestr.length - 5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
}
var other = this.id == "from" ? "#to" : "#from";
var option = this.id == "from" ? "maxDate" : "minDate";
if ((selectedDate = $(other).val()).length > 0) {
year = selectedDate.substring(selectedDate.length - 4, selectedDate.length);
month = jQuery.inArray(selectedDate.substring(0, selectedDate.length - 5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker("option", option, new Date(year, month, 1));
}
}
});
$("#btnShow").click(function() {
if ($("#from").val().length == 0 || $("#to").val().length == 0) {
alert('All fields are required');
} else {
alert('Selected Month Range :' + $("#from").val() + ' to ' + $("#to").val());
}
});
The code seems to work fine in JQuery 2.1.4 with JQuery-UI 1.11.4: https://jsfiddle.net/sLfga1jt/3/
Have you verified that your script tags are loading and in the proper order? Jquery script reference should be before Jquery-UI.
Also verify that the javascript from http://techbrij.com/month-range-picker-jquery-ui-datepicker is loaded after the script references by including in a script tag after jquery (as shown in example) or by wrapping in the document ready or similar function to ensure code is run after all the scripts are loaded:
<div style="text-align:center;">
<label for="from">From</label>
<input type="text" id="from" name="from" readonly="readonly" />
<label for="to">to</label>
<input type="text" id="to" name="to" readonly="readonly" />
<input type="button" id="btnShow" value="Show" />
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$( "#from, #to" ).datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
},
beforeShow : function(input, inst) {
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length-4, datestr.length);
month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
$(this).datepicker('setDate', new Date(year, month, 1));
}
var other = this.id == "from" ? "#to" : "#from";
var option = this.id == "from" ? "maxDate" : "minDate";
if ((selectedDate = $(other).val()).length > 0) {
year = selectedDate.substring(selectedDate.length-4, selectedDate.length);
month = jQuery.inArray(selectedDate.substring(0, selectedDate.length-5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker( "option", option, new Date(year, month, 1));
}
}
});
$("#btnShow").click(function(){
if ($("#from").val().length == 0 || $("#to").val().length == 0){
alert('All fields are required');
}
else{
alert('Selected Month Range :'+ $("#from").val() + ' to ' + $("#to").val());
}
});
</script>

MVC Calendar values not saved to database after creating

Create view
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<br />
<label>Start Time</label>
<br />
<div class="dp">
<input type="text" class="form-control" id="datetimepicker6" />
</div>
</div>
</div>
Javascript for calendar
<script type="text/javascript">
var array = ["2015-12-25", "2015-12-24", "2015-12-31"]
$('.datepicker').datepicker({
beforeShowDay: function (date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return [array.indexOf(jQuery.datepicker.formatDate('yy-mm-dd', date)) == -1]
} else {
return noWeekend;
}
}, minDate: 0
});
$(function () { $('#startDate').datepicker({ beforeShowDay: $.datepicker.noWeekends }); });
$(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datetimepicker6').datetimepicker({
minDate: new Date(currentYear, currentMonth, currentDate), daysOfWeekDisabled: [0, 6],
disabledDates: [
moment("12/25/2015"),
moment("12/24/2015")
]
});
$('#datetimepicker7').datetimepicker({
minDate: new Date(currentYear, currentMonth, currentDate), daysOfWeekDisabled: [0, 6],
disabledDates: [
moment("12/25/2015"),
moment("12/24/2015")
]
});
});
</script>
I have a create action where I can choose the startDate and EndDate using a calendar. But after I select the dates and create, the dates don't get saved in the database but other values in the same form do. Thus it doesn't appear in the table as well. How do I solve this?
Your manually generating the <input> element but not giving it a name attribute so its value is not posted back. The name attribute needs to match the name of your model property, and the best way to generate this is to use the strongly typed html helpers
#Html.TextBoxFor(m => m.yourPropertyName, new { #class = "form-control" })
which will generate an id attribute id="yourPropertyName" so that the script can refer to $('#yourPropertyName').datetimepicker(). Alternatively, you can give it a different id attribute using new { #class = "form-control", id="datetimepicker6" }

How to select date on click from Bootstrap Datepicker

I have Bootstrap Datepicker and I want to set default date when click on Set Date button.
HTML
<div class="input-append date datepicker no-padding" data-date-format="dd-mm-yyyy">
<input class="input-medium" id="date" size="16" type="text"><span class="add-on"><i class="icon-th"></i></span>
</div>
Set Date
jQuery
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07/01/2015";
$("#date").val(date);
});
});
I set date using jQuery but it do not show as selected date. My question is How to set date on click and show as selected date.
JS Fiddle
read this http://api.jqueryui.com/datepicker/#method-setDate
here after update your example
http://jsfiddle.net/tuG6C/614/
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07-01-2015";
//$("#date").val(date);
$( '.datepicker' ).datepicker( "setDate", date );
});
});
Update your javascript with
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07/01/2015";
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var today = curr_month + "/" + curr_day + "/" + curr_year;
$("#date").val(today);
});
});
check js fiddle
http://jsfiddle.net/swapnilmotewar/tuG6C/609/
Please replace:
$("#date").val(date);
With:
$(".datepicker").datepicker("update", date);

Jquery functions does not work on dynamic generated form component?

I'm using this jQuery function with jQuery UI to generate a datepicker when the user hits one textfield:
<script>
$(function() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
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 );
}
});
});
</script>
As you can see it respond to the textfields from and to. The textfields are in my html code like:
<div class="clearfix">
<label for="from">From</label>
<input type="text" id="from" name="from" class="xlarge"/>
</div>
<div class="clearfix">
<label for="to">to</label>
At this point everything works. Later, in the same form a let the user to clone this form elements using this other code:
$(document).ready(function() {
var removeButton = 'remove';
$('#addl').click(function() {
$('div.jobitems:last').after($('div.jobitems:first').clone());
$('div.jobitems:last').append(removeButton);
$('div.jobitems:last input').each(function(){
this.value = '';
});
});
$('#remove').live('click', function() {
$(this).closest('div.jobitems').remove();
});
});
<input type="text" id="to" name="to" class="xlarge"/>
</div>
When the user clone the elements, the new ones do not respond to the function that generates the datepicker. I'm really confused about this. Here you can check the running code: http://domingo.net46.net/example/reg.php
You have to call the function that make the datapicker happen again after the append of the html elements so that the datepicker work on them because i can see that the datepicker function is called on the document ready and you have another function that append html element so you have to call the datepicker function right after you append the html elemnt.
$(DoAction);
function DoAction() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
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 );
}
});
}
$(document).ready(function() {
var removeButton = 'remove';
$('#addl').click(function() {
$('div.jobitems:last').after($('div.jobitems:first').clone());
$('div.jobitems:last').append(removeButton);
$('div.jobitems:last input').each(function(){
this.value = '';
});
DoAction();
});
$('#remove').live('click', function() {
$(this).closest('div.jobitems').remove();
});
});
The issue could be on the line that is as follows:
this.value = '';
Try changing this to become:
$(this).value = '';
Then it should work as it's creating a jQuery object
If the cloned elements have the same id as the originals, I'm not surprised that the datepicker will only act on the first elements it finds.

Categories