Hello every body i need help with moment js i've an input field called Start and another called stop
start = moment().format('LT'); // works when i click on the play button
stop = moment().format('LT'); // works when i focus on the counter input beside the play button --> for test
i want to change the start input field manually so i want a validation function that takes the input value and check if the input is valid or not on this form LT for ex: when i delete the value of the input which is 6:39 PM as below in the picture and type for example 6:02:00 PM or 1:00 PM or add a string 5:dfds2 PM i want to console log any error message and return the previous value to the input again also when i remove the current value and add a number like '1 for example' without am or pm so it determines if the number is before or after than stop input value and type in the input field like this 1:00 AM or 1:00PM i used this function to validate the start input field but it gives me wrong answers
function validate(inputVal) {
let temp =this.startTime;
let x = temp;
if(moment(inputVal, "hh:mm").isValid()) {
x= moment(inputVal, "HH:mm").format('hh:mm A');
console.log("inputVal is: " + inputVal + " and x is: " + x);
this.startTime = x
} else {
this.startTime = "temp";
console.log("no");
}
}
here is the pic
for more info u can visit toggl website my idea is taken from there
any help ?! thanx in advance
I went ahead and cleaned up your function a bit, reduced the logic, now you should just make sure the moment format is what your looking for
function validate(val) {
let parsedTime = moment(val, "hh:mm");
if (parsedTime.isValid()) {
this.startTime = parsedTime.format('hh:mm A');
}
}
Related
I'm new to javascript so I apologize if this is a very basic question.
I am building (Drag & drop) forms for user input of data through a website. I have two time inputs (STARTTIME and TESTTIME) that are in HH:MM format. I need to display the time 15 minutes after STARTTIME (15MIN) and the number of minutes that have passed between STARTTIME AND TESTTIME (TIMEDIF).
The website provides the drag & drop form editor and has a field where I can add javascript to the form.
I've figured out how to take string inputs of "HH:MM" and output the values I need.
I am struggling with extracting the input from the two time fields (STARTTIME and TESTTIME) and writing to the 15MIN and TIMEDIF fields.
For returning the input from the form, I've tried using:
var atime = $("#" + STARTTIME + "input");
var ttime = $("#"+ TESTTIME + "input");
//-or-
var atime = $("div[id=STARTTIME] input");
var ttime = $("div[id=TESTTIME] input");
//and for setting the 15MIN and TIMEDIF variables
$("div[id=15MIN] input").val(tqtime);
$("div[id=TIMEDIF] input").val(difftime);
//tqtime and difftime are in "HH:MM" and number format, respectively and are calculated from atime and ttime.
I have tested the output of the code from atime and ttime defined as "HH:MM" strings to tqtime and difftime, which has been successful.
However, all variables are undefined when used with the form, leading me to believe that I'm not returning the input correctly.
When you call $("someselector"), what you get is a jQuery element. This is more than just the value of the input, and thus you must actually call a function to get that value. With jQuery, you use the .val() method to achieve this. Assume that "#" + STARTTIME + input" and "#" + TESTTIME + "input" are ids of input elements, getting the values would look like this:
var atime = $("#" + STARTTIME + "input").val();
var ttime = $("#" + TESTTIME + "input").val();
I am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
Creates a variable 'total' with a value of 0.
Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
If the user enters a number, add the new number to a running total.
If the user enters the word "quit" the loop should stop execution.
If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping.
Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".
small issue with date.
I'm trying to format a date when user type the value. So if someone type, for example, 2017, the input auto complete with / (slash) and then the user fill the month and the day.
Currently I have this code, but doesn't work as expected. I mean, the date must have the format: YYYY/MM/DD.
$('input[name*=expire]').bind('keyup', function() {
// Instance vars.
var $this = $(this),
value = $this.val();
// Clear value to inter number.
value = value.replace(/\D/g,"");
value = value.replace(/(\d{4})/,"$1");
value = value.replace(/(\d{2})(\d)/,"$1/$2");
value = value.replace(/(\d{2})(\d)$/,"$1/$2");
// Set interval to map click action.
setTimeout(function () {
$this.val(value);
}, 1);
});
Using this code, for some reason the return is 11/11111/1 instead of 1111/11/11.
Thank you in advance.
I am learning javascript and at the same time trying to create a simple script that allows you to type a foreign language on a web browser with your keyboard.
So, when you type a for example, there is a single letter mapped to a, so a single character Դ would appear, however to make a character like 厄 appear, you have to type twice, since this language has more characters than the English alphabet.
So, the problem is with that last character. Normally, I should have to type g and h consecutively in the span of one second to produce the 厄 letter, but I have problems waiting to check if within two characters have been typed within one second of eachother inorder to show that letter.
So, I don't think time interval functions are the way to go about this, but I can't see any other method also.
cautions: check key whether up in keydown() & notify keydown the key is upped in keypress();
var start = null;
$('#in').keydown(function (e) {
if (!start) {//checking is a new user input
start = $.now();
}
}).keyup(function (e) {
var timeElapsed = $.now() - start;
start = null;//start the next timing tracking
console.log(['time elapsed:', timeElapsed, 'ms'].join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<h2>please input some letter to test</h2>
<input id="in"/>
</label>
another answer about your question,perhaps this is your truly answer.
function duration(timestamps) {
var last = timestamps.pop();
var durations = [];
while (timestamps.length) {
durations.push(last - (last = timestamps.pop()));
}
return durations.reverse();
}
function display(mills) {
if (mills > 1000)
return (mills / 1000) + ' s';
return mills + ' ms';
}
var durations = [];
$('#in').keydown(function (e) {
durations.push($.now());
}).keyup(function (e) {
var current = durations;
current.push($.now());
durations = [];
var timeElapsed = current[current.length - 1] - current[0];
console.log([
['time elapsed:', display(timeElapsed)].join(' '),
['keys duration:', duration(current).map(display)].join(' ')
].join(' --- '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<h2>Please input something to test!</h2>
<input id="in"/>
</label>
Below is the sample code to measure the elapsed time between any 2 events.
I added setTimeout just to give you an example.
var startTime = Date.now();
setTimeout(function(){
var elapsedTime = Date.now() - startTime;
console.log('elapsedTime ='+elapsedTime);
}, 100);
Like Alex mentioned, for every press, simply store new Date().getTime(); in a variable, which will get you the latest UTC time. UTC time is given in milliseconds, so on the next key-press, just see if the current time and the stored time differ by 1000!
I am selecting time slot on dragging on time slot cell. After selecting time slot, I enter patient name in textbox and click on select button then patient name goes to selected time slot. The user can select multiple time slot for multilpe patient name and onclick of allot button I have to insert patient name with time slot (From time To time) to database.
I have problem in getting alloted time slot ie.From time and To time in jquery.
$("#btnAllot").click(function () {
//how i get alloted time here.
$('tr').each(function () {
$(this).find('td').each(function () {
if ($(this).hasClass('yell')) {
alert($(this).closest('tr').find('td:eq(0)').text());
};
});
});
}
see jsbin on dragging on time slot cell
Ok, here is one way to do it:
You iterate over each row whose third cell has a rowspan attribute. This indicates the start of a new appointment. You can get the start time by examining the siblings (sort of) and the end time by getting the row that is rowspan - 1 elements away.
There might be better ways, but this might give you a start.
For example:
var find_closest_hour = function($row) {
var $cell = $row.children('td:first-child'),
hour = "";
// probably add something here
while($cell.length && !(hour = $.trim($cell.text()))) {
$cell = $cell.parent().prev().children('td:first-child');
}
return hour;
};
var $all_tds = $('#tableAppointment tr td:nth-child(3)'),
$tds = $all_tds.filter('[rowspan]');
// will contain a list of objects [{patient: name, start: time, end: time},...]
var appointments = $tds.map(function() {
var $this = $(this),
$row = $this.parent(),
$cells = $row.children('td'),
patient = $.trim($this.text()),
start = find_closest_hour($row).split(':', 1) + ":" + $.trim($cells.eq(1).text()),
$end_row, end;
if(this.rowspan == 1) {
end = start;
}
else {
$end_row = $all_tds.eq($all_tds.index(this) + this.rowSpan - 1).parent();
end = find_closest_hour($end_row).split(':', 1) + ":" + $.trim($end_row.children('td').eq(1).text());
}
return {patient: patient, start: start, end: end};
}).get();
DEMO
I will let you figure out how to format the times properly ;)
Note: This very much depends on your current table structure and is likely to break if you change it. To make things more flexible, you could add classes to cells that contain the important information, for example hour to each first cell that contains the hour of the day and appointment_start to the cell of an appointment. Then you could search for/filter by these.