I have following code
$(this).datepicker({ minDate: 0,
onSelect: function(dateText, inst) {
var sdate = $(this).val();
var cnt = $(".txtdate[value='" + sdate + "']").length;
if (cnt == '0')
return true;
else {
alert('You have planned for this date');
return false;
}
}
});
i want to stop user to select duplicate date , i am able to do compare and everything, i am stuck at one place,
I am returning false to not select the date
but still its selecting date
what i am doing wrong in code
Please help
Thanks
$(this).datepicker({ minDate: 0,
onSelect: function(dateText, inst) {
var sdate = $(this).val();
var cnt = $(".txtdate[value='" + sdate + "']").length;
if (cnt == '0')
return true;
else {
alert('You have planned for this date');
$(this).val(' ')
return false;
}
}
});
Related
I am working on a Razor Page Web App In Asp Core and I am using this code to generate calendars with html and java script. When I click on a day of a calendar, I am being redirected to a page. In that page I will need to retrieve some data from my Model class based on the day that was selected by the user.
Is there any way I can save the clicked date to use in my Razor Page class ?
Here is the js code:
function myFunction() {
function calendar() {
var padding = "";
var totalFeb = "";
var i = 1;
var current = new Date();
var cmonth = current.getMonth();
var day = current.getDate();
var tempMonth = month + 1; //+1;
var prevMonth = month - 1;
if (month == 1) {
if ((year % 100 !== 0) && (year % 4 === 0) || (year % 400 === 0)) {
totalFeb = 29;
} else {
totalFeb = 28;
}
}
var monthNames = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"];
var totalDays = ["31", "" + totalFeb + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
var tempDate = new Date(tempMonth + ' 1 ,' + year);
var tempweekday = tempDate.getDay();
var tempweekday2 = tempweekday;
var dayAmount = totalDays[month];
while (tempweekday > 0) {
padding += "<td class='premonth'></td>";
tempweekday--;
}
while (i <= dayAmount) {
if (tempweekday2 > 6) {
tempweekday2 = 0;
padding += "</tr><tr>";
}
if (i == day && month == cmonth) {
padding += "<td class='currentday' onclick='redirect();' onMouseOver='this.style.background=\"#00FF00\"; this.style.color=\"#FFFFFF\"' onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#00FF00\"'>" + i + "</td>";
} else {
padding += "<td class='currentmonth' onclick='redirect();' onMouseOver='this.style.background=\"#00FF00\"' onMouseOut='this.style.background=\"#FFFFFF\"'>" + i + "</td>";
}
tempweekday2++;
i++;
}
var calendarTable = "<table class='calendar'> <tr class='currentmonth'><th colspan='7'>" + monthNames[month] + " " + year + "</th></tr>";
calendarTable += "<tr class='weekdays'> <td>Sun</td> <td>Mon</td> <td>Tues</td> <td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarTable += "<tr>";/ calendarTable += padding;
calendarTable += "</tr></table>";
document.getElementById("calendar").innerHTML += calendarTable;
}
function go12() {
for (i = 6; i < 12; i++) {
calendar(i);
}
}
if (window.addEventListener) {
window.addEventListener('load', go12, false);
} else if (window.attachEvent) {
window.attachEvent('onload', go12);
}
})();
function redirect() {
window.location.replace("./MyPage");
}
In my Razor page:
public class MyPageyModel : PageModel
{
private readonly ILogger<MyPageModel> _logger;
public PrivacyModel(ILogger<MyPageModel> logger)
{
_logger = logger;
}
public void OnGet()
{
//somewhere in this class I need a DateTime variable that represents the day that the user clicked on the calendar
}
}
}
EDIT
Based on #Wowo Ot response, I tried something like this to send the data to my class using OnPostMethod:
function redirect() {
$.ajax({
type: 'POST',
url: './MyPage',
dataType: 'string',
data: { day: $("#DAY").val() },
success: function (result) {
return true;
},
error: function (ex) {
return false;
}
});
}
And in my Razor Page:
public string OnPostSetDate(int day)
{
try
{
Debug.WriteLine(day);
return "OK";
}
catch (Exception)
{
return "Error";
}
}
But now I get an error: "Failed to load resource: the server responded with a status of 500 () [https://localhost:44350/MyPage]"
try this
in your controller
[HttpPost]
public string setDatePost(int day, int month, int year)
{
try
{
DateTime theDate = new DateTime(year, month, day);
// your code to save Date
return "OK";
}
catch (Exception)
{
return "Error";
}
}
in your page script
<script type="text/javascript">
$(document).ready(function () {
$("#CLK").click(function () { // this is your button for selecting the day
$.ajax({
type: 'POST',
url: '#Url.Action("setDatePost")', // the name of your action (function) in controller
dataType: 'string',
// these field represent your selection of day, month and year
data: { day: $("#DAY").val(),month: $("#MONTH").val(), year: $("#YEAR").val() },
success: function (result) {
return true;
},
error: function (ex) {
return false;
}
});
return false;
})
});
</script>
Am using an editable HTML datatable on my asp.net web page .Which look like this,
How to add validation on column Target, to receive only float values.?
Function (For enable edit):
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = aData[0];
jqTds[1].innerHTML = aData[1];
jqTds[2].innerHTML = '<input type="text" id="Float" class="form-control" value="' + aData[2] + '">';
jqTds[3].innerHTML = '<a class="save-row" href="">Save</a>';
jqTds[4].innerHTML = '<a class="cancel-row" href="">Cancel</a>';
}
I tried to add keypress event on the textbox , but its not working.!
$('#Float').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which != 8)) {
event.preventDefault();
}
});
Am new to jquery so please help me solve this ?
Try:
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
Note: Above code doesn't work for -ve values.
just like in my questions, i have 2 calendars to be selected by users, and i would like to get the total selected days and be displayed in label.
users have to select the start date in lstartdate calendar and end date in lenddate calendar.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}
if (cstart.SelectedDate <= cend.SelectedDate)
{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
Double Value;
if (cend.SelectedDate >= cstart.SelectedDate)
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
else
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
total.Text = // ?
}
}
}
im not sure if the code arrangements are correct or not. do help and tq :)
TRY LIKE THIS
DateTime DtF = ceFromDate.SelectedDate.Value;
DateTime D1T = ceToDate.SelectedDate.Value;
double dd = (DtF - D1T).TotalDays;
total.Text = dd.ToString();
Here is simple way to get different between two dates
class Program
{
static void Main(string[] args)
{
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
}
}
Source
you need to implement it yourself..
Convert the difference between the two dates into a TimeSpan, then get the amount of Days of that TimeSpan and set this as your text-value.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}else{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
TimeSpan duration = DateTime.Parse(cend.SelectedDate ).Subtract(DateTime.Parse(cstart.SelectedDate ));
total.Text = duration.Days.ToString();
}
}
}
I have a textbox and i need to validate that it accepts only 1,1.5,2,2.5,3,3.5,...11.5
How to validate it.. pls tell the answer please.
$(document).on('keyup', '#Dia_Inch', function (e) {
Dia_Inch = $(this).val();
if (Dia_Inch.charAt(1) == ".") {
if (Dia_Inch.charAt(2) != "5") {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
}
var val = isNumberInch(e);
if (val == false || Dia_Inch > 11.5) {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
});
this my sample code.. but it wont be worked.
You can do this using jquery:
function validate(value){
var arr = [1,1.5,2,2.5,3,3.5,...11.5];
if($.inArray(value, arr) >= 0){
return true;
}
return false;
}
You'll have to modify this according to your needs.
Here is a fiddle: http://jsfiddle.net/5Cm2w/
Do not forget to update the array with your actual values.
This may solve your purpose.
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^\d+(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo
But if u want to allow up to 11.5 then
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^[1-9]{1}[1]{0,1}(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo
I have played with:
https://github.com/experteer/autocompleteTrigger/
as following:
(function ($, window, document, undefined) {
$.widget("ui.autocompleteTrigger", {
//Options to be used as defaults
options: {
triggerStart: "%{",
triggerEnd: "}"
},
_create: function () {
this.triggered = false;
this.triggered2 = false;
this.element.autocomplete($.extend({
search: function () {
/**
* #description only make a request and suggest items if acTrigger.triggered is true
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (acTrigger.triggered == true || acTrigger.triggered2 == true) {
return true;
} else {
return false;
}
},
select: function (event, ui) {
/**
* #description if a item is selected, insert the value between triggerStart and triggerEnd
*/
var acTrigger = $(this).data("autocompleteTrigger");
var text = this.value;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
var cursorPosition = acTrigger.getCursorPosition();
var lastTrigger1Position = text.substring(0, cursorPosition).lastIndexOf(trigger);
var lastTrigger2Position = text.substring(0, cursorPosition).lastIndexOf(trigger2);
var lastTriggerPosition;
if (lastTrigger1Position > lastTrigger2Position) {
lastTriggerPosition = lastTrigger1Position;
} else {
lastTriggerPosition = lastTrigger2Position;
}
var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) + ui.item.value +
acTrigger.options.triggerEnd;
this.value = firstTextPart + text.substring(cursorPosition, text.length);
acTrigger.triggered = false;
acTrigger.triggered2 = false;
// set cursor position after the autocompleted text
this.selectionStart = firstTextPart.length;
this.selectionEnd = firstTextPart.length;
return false;
},
focus: function () {
/**
* #description prevent to replace the hole text, if a item is hovered
*/
return false;
},
minLength: 0
}, this.options))
.bind("keyup", function (event) {
/**
* #description Bind to keyup-events to detect text changes.
* If the trigger is found before the cursor, autocomplete will be called
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {
var text = this.value;
var textLength = text.length;
var cursorPosition = acTrigger.getCursorPosition();
var lastString;
var query;
var lastTriggerPosition;
var lastTriggerPosition2;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
if (acTrigger.triggered && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupFirst');
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
$(this).autocomplete("search", query);
}
if (acTrigger.triggered2 && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupSec');
lastTriggerPosition2 = text.substring(0, cursorPosition).lastIndexOf(trigger2);
query = text.substring(lastTriggerPosition2 + trigger2.length, cursorPosition);
$(this).autocomplete("search", query);
}
else if (textLength >= trigger.length) {
// set trigged to true, if the string before the cursor is triggerStart
lastString = text.substring(cursorPosition - trigger.length, cursorPosition);
acTrigger.triggered = (lastString === trigger);
acTrigger.triggered2 = (lastString === trigger2);
}
}
});
},
/**
* #description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
*/
destroy: function () {
// this.element.removeStuff();
// For UI 1.8, destroy must be invoked from the
// base widget
$.Widget.prototype.destroy.call(this);
// For UI 1.9, define _destroy instead and don't
// worry about
// calling the base widget
},
/**
* #description calculates the the current cursor position in the bound textfield, area,...
* #returns {int} the position of the cursor.
*/
getCursorPosition: function () {
var elem = this.element[0];
var position = 0;
// dom 3
if (elem.selectionStart >= 0) {
position = elem.selectionStart;
// IE
} else if (elem.ownerDocument.selection) {
var r = elem.ownerDocument.selection.createRange();
if (!r) return data;
var tr = elem.createTextRange(), ctr = tr.duplicate();
tr.moveToBookmark(r.getBookmark());
ctr.setEndPoint('EndToStart', tr);
position = ctr.text.length;
}
return position;
}
});
})(jQuery, window, document);
and in the View:
$('input,textarea').autocompleteTrigger({
triggerStart: '#',
triggerEnd: '',
triggerStart2: '##',
sourceOption1: '/UITests/LookupFirst',
sourceOption2: '/UITests/LookupSec'
});
Controller Action Method(LookupSec is identical) is:
public ActionResult LookupFirst(string q)
{
var list = new List<string>()
{
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
};
IEnumerable<string> data;
if (q != null)
{
data = list.Where(x => x.StartsWith(q));
}
else
data = list;
return Json(data, JsonRequestBehavior.AllowGet);
}
Now it supports two triggers # and # and two datasources for each one...
Problem is the searching doesnt work anymore, everything works as expected "Almost" but when i type something like "#as" it should filter the result but it doesnt!
any idea why this is not working ?
You seem to be using the LookupSec action to filter with the # character but in your question you have only shown the LookupFirst action which is associated with the # filter character. I have tested your code and it worked for # and not for # because LookupSec doesn't exist.
Once I have defined the LookupSec controller action it worked for both. Just be careful as right now you have hardcoded those action names in the widget itself so the sourceOption1 and sourceOption2 parameters will be completely ignored.
The query string parameter used by jquery autocomplete is called term, not q so fix your controller action as right now it isn't filtering anything:
public ActionResult LookupFirst(string term)
{
...
}