Javascript time helper? -Interesting problem! - javascript

I am new to the world of javascript and even trying google search has not really helped me find what I am looking for.
So I have come here in the hope you can point me in the right direction.
RULE= It must not be click! Can be done by tabbing!
I have many text fields which the user will input times that have been recorded.
E.g. Event 1 happened at 11:31am
Event 2 happened at 11:59am
I want to make this process as easy as possible for the user by having the textbox formatted in hours and seconds in 24hr format:
So the textbox value= 00:00 and when the user selects the text box they can enter the hours part. Then it will jump to the seconds part.
Any idea if there is something that can do that if so could you link me. If not could you give me an idea of what the coding will be like and if there are easier alternatives.
I have made some pseudo code to help you understand my implementation goal:
for count = 0 , while count is less than 20, count++
{
create a texbox with name time+count, set the value to ="00:00"
}
when the user enters numbers they go into the hour segment until that is completed
the script then jumps the cursor to the minutes segment
if time+count+1 is lesser thatn time+count message user that time error "An event cannot occur before the previous event"
Thankyou for hearing me out!

I don't really know of any time pickers that would suit your needs, but here's a basic idea of how one would be implemented:
You have two textboxes, or multiple pairs of textboxes
In each textbox, you put an event handler to handle "onkeyup" event
In onkeyup handler, check if lenght of text in box is 2
If length is 2 -> focus the next textbox
This way the user can simply keep on typing the numbers.
You may need to add some additional checks into the event listener, for example to make sure that if the user comes back to the field, they can edit it easily (eg. if they press shift-tab, it won't focus an incorrect field)
If you wanted to be really fancy, you could have a single textbox for times. Then, each time user presses a key, you'd check if it's a number. If user first types two numbers, it would then insert a : as the separator if the third key is a number, and so on.

This might be a beginning. Using jQuery this is not such a painful task.
http://jsfiddle.net/sArjQ/
for(var i = 0; i < 20; i++) {
var input = $("<input>", { name: 'time' + i, // create input element
val: '00:00' });
input.click(function() {
$(this).prop({ selectionStart: 0, // move caret to beginning on click
selectionEnd: 0 });
}).keydown(function() {
var sel = $(this).prop('selectionStart'),
val = $(this).val(),
newsel = sel === 2 ? 3 : sel; // so that it moves two positions for :
$(this).val(val.substring(0, newsel) // automatically set value
+ val.substring(newsel + 1))
.prop({ selectionStart: newsel, // move caret along
selectionEnd: newsel });
});
$('body').append(input);
}

Related

How to hide text in input field as you type each character?

I have an input field, that basically takes a confirmation code(alphanumerical) while logging into an application. I want to implement the below functionality:
when you type each character, it appears in the text field for a fraction of time(say 1 second), and then it becomes an asterisk.
The reason I want this? This helps the user know what character he/she is typing in the input field and doesn't compromise on the security aspects.
What I have tried? I tried to make the input field type as "password" but that makes the character typed into an asterisk instantly. I don't want this, I want it to show for 1s then become an asterisk.
<input type=password placeholder="Please enter your alphanumerical code" />
Note: I don't want a display/hide toggle button implementation of the above, as I already am aware of that, and have seen answers about that, but it's not my intended implementation
I am working on a reactJS application, so an implementation based on react, JS, JSX, HTML, etc. would be preferred. Thanks :)
P.S This is my first question on stack overflow and I am very new to react, so please pardon me for any mistakes. Feel free to ask any doubts/queries you have regarding the question.
There is a ready-made solution for github: https://karaggeorge.github.io/react-better-password/
Consider the following algorithm:
On input:
get the caret position,
get the number of characters added or deleted
If added,
get the added characters
insert them in the shaddow string
// to do
after a defined time, or on next input, replace
added characters with asterisks (*)
If deleted
delete number deleted to the right of character pos
in the shadow string
Masking the characters runs on a timeout. If something is entered before the timeout runs, the timeout is cancelled and the characters masked immediately. If you type really quickly, multiple characters are visible for a very short time. If multiple characters are pasted, they are all displayed for the timeout lag.
Here's an implementation:
let maskInput = (function() {
// Keep reference to timeout
let timeoutRef = null;
// Set field to all asterisks, keep cursor at current position
function blankField(el) {
// Cancel timeout if there is one
if (timeoutRef) {
clearTimeout(timeoutRef);
timeoutRef = null;
}
// Get cursor position
let cursorPos = el.selectionStart;
// Mask values
el.value = el.value.replace(/./g, '*');
// Put cursor back in position
el.setSelectionRange(cursorPos, cursorPos);
}
return function (el) {
// Get the shaddow element
let inp = document.getElementById('i1');
// Get current cursor position
let cursorPos = el.selectionStart;
// Get number of characters added
let numAdded = el.value.length - inp.value.length;
// If characters were added
if (numAdded > 0) {
// Get characters added
let charsAdded = el.value.slice(cursorPos - numAdded, cursorPos);
// Insert characaters in inp
let insertIdx = cursorPos - numAdded;
inp.value = inp.value.substring(0, insertIdx) +
charsAdded +
inp.value.substring(insertIdx, inp.value.length);
timeoutRef = setTimeout(() => blankField(el), 250);
// If characters were deleted, delete numAdded characters
// to the right of the current cursor position in inp
} else if (numAdded < 0) {
inp.value = inp.value.substring(0, cursorPos) +
inp.value.substring(cursorPos - numAdded, inp.value.length);
}
}
}());
<input id="i0" oninput="maskInput(this)">Enter text<br>
<input id="i1" readonly>Shaddow text
This assumes that the listener is on an input element, plus the ID of the shadow input and masking character are hard coded. Both can easily be dynamic or set in a parameter object or similar.

Custom time increments for Kintone's time fields

In Kintone, the time field currently increments by 30 minutes, but is there a way with JavaScript to change this increment, say, by 10 minute increments?
I know this doesn't fit well with Kintone's JavaScript coding guidelines, but would changing the DOM structure of the time field to show 10 minute increments be the correct way to move forward?
Like you said, this is probably possible by editing the DOM, but not the best option since the customization may not work after any update.
As an alternative or a better choice, you can create two drop-down fields, "hour" on one of the them and "minute" on the other field.
Thanks Yuzo
I tried out your solution to see what it's like, and found out it was actually a good alternative.
I currently have it working with the 24 hour clock format, as below.
gif image of customization
(function() {
"use strict";
// "hours" -> field code of Hours field
// "minutes" -> field code of Minutes field
// "time" -> field code of Time field
kintone.events.on(['app.record.create.submit','app.record.edit.submit','app.record.index.edit.submit'], function (event) {
var hourvalue = event.record.hours.value;
var minutevalue = event.record.minutes.value;
event.record.time.value = hourvalue + ":" + minutevalue;
return event;
});
})();
My team prefers to work with 12 hour clock format though, so I added in a radio button field to represent AM and PM. I also changed the drop down to only include selections from 0 to 11.
I edited my code a bit more so that the selected hour number will get a +12 before being entered into the time field, but I keep getting an error, "event.record['time'].value is invalid.". Not really sure why this should be happening. This is my new code:
(function() {
"use strict";
// "hours" -> field code of Hours field
// "minutes" -> field code of Minutes field
// "time" -> field code of Time field
// "ampm" -> field code of radio button field that has selections of AM and PM
kintone.events.on(['app.record.create.submit','app.record.edit.submit','app.record.index.edit.submit'], function (event) {
var hourvalue = event.record.hours.value;
var minutevalue = event.record.minutes.value;
if (event.record.ampm.value == "PM"){
hourvalue = hourvalue + 12;
}
event.record.time.value = hourvalue + ":" + minutevalue;
return event;
});
})();
I did some test regarding what you are doing.
It seems like the error you are seeing appears only when the field type that you are returning
to in the script does not match the actual field type that you have placed in the form.
So I assume when you changed your form to make it as the 12 o'clock format,
you might have changed the field that you put the value into to a time field,
which before it was a text field.
Can you check into it?
I will put a link below regarding the field types just for your reference
kintone developer network - Field Types https://developer.kintone.io/hc/en-us/articles/212494818-Field-Types
I think the drop-down field returns a string value.
Therefore, you need to convert it to a number by using parseInt function before hourvalue like hourvalue(hourvalue + 12). Thanks.

Meteor: How to set a number based on the number of checked boxes within a section

I currently have a multi-section form, with a number of checkboxes. What Im trying to do, is show the number of checked boxes, next to the total. I have total showing up just fine, but I cant for the life of me figure out a way to loop over the inputs, successfully find the :checked, and print that number out.
I think the main thing causing me issues, is that it needs to update every time a new box is checked. Heres some of the code.
Event Handler
'click input[type=checkbox]': function(){
Session.set('selectedPlayerCount', n);
Session.get('selectedPlayerCount');
}
The goal here is to set the number of selected players, and pass it to the template/helper.
Helper
countSelected: function(){
n = 0;
n++;
var selectedPlayerCount = Session.get('selectedPlayer');
return selectedPlayerCount;
}
Within the helper I'm attempting to iterate every time the event is triggered, and as a result increase the value by one. I'm aware that resetting n back to 0 is going to cause some issues, and I know that needs to be changed one the rest is figured out. I just cant figure out where the variable needs to be set in order to provide a default value.
Template
<header>
<p>{{ countSelected }}</p>
</header>
All I'm trying to do here for now is to print out the value rendered by the helper. I don't believe this is causing any issues.
TL;DR - How to count number of checked inputs within a section of a form, and for each one, increment a value, and then return it every time its changed.
I'm new to this but maybe this will serve: define your account to zero in a session variable, each time you select a checkbox you increase the value of your session variable
Session.set("countPlayersChecked", 0);
Template.proof.helpers({
countSelected: function () {
return Session.get("countPlayersChecked");
}
});
Template.proof.events({
'click input[type=checkbox]': function (event) {
if($(event.target).is(':checked'))
Session.set("countPlayersChecked", Session.get("countPlayersChecked")+1);
else
Session.set("countPlayersChecked", Session.get("countPlayersChecked")-1);
}
});
Hope it serves.

Slowly change a value with javascript

I'm making a prototype of an interface for boats. Details aside, I have created a numpad using javascript onClick that lets you input a value and then send that value to another field, let's call it "current". Is there a way to make the "current" field I'm sending to slowly increase until it reaches the value i send from my numpad?
For example, if I enter the number 24 on my numpad and click "submit", the "current" field shows 24 right away, but I would like for it to slowly tick up to 24 in increments. This might sound like a silly detail but it would make quite a difference for my prototype.
Thanks in advance!
You can use javascript's setInterval function:
var handle;
function func() {
// Increment the value by 1
if(necessary value is reached) {
window.clearInterval(handle);
}
}
handle = window.setInterval("func", 50); // Run each 50ms

jquery masked input plugin to not clear field when errored

I'm looking at the http://digitalbush.com/projects/masked-input-plugin/
I'm calling it like this:
$(control).mask('999-999-9999');
And I don't want it to throw away the users input if something is wrong, e.g. they haven't finished
[407-555-____]
If you leave the field after having typed this much, it clears it. I'd like to leave it so they can finish later.
I'm new to jQuery, and I've looked through his source, but I can't find any way to do that, nor can I find any way to edit it to accomplish what I want, because the code is arcane to my eyes.
Set autoclear option to false.
$(control).mask('999-999-9999', {autoclear: false});
It looks like I should just make the whole mask optional:
mask('?999-999-9999')
That way the control thinks what the user has is "valid" and I can continue. Even though it isn't really the optional part of the mask.
You should delete statement input.val(""); in checkVal() function for a proper solution.
If you're using minified version, you should search and delete statement:
if(!a&&c+1<i)f.val(""),t(0,k);else
Try update file jquery.maskedinput.js
In function function checkVal(allow) set parameter allow on true. Its help for me.
function checkVal(allow) {
allow = true; ///add this command
//..............
}
In addition to removing the input.val("") in checkVal() you can also change the call to clearBuffer.
In the original code it is: clearBuffer(0, len); removing all user input.
if you change this to clearBuffer(lastMatch + 1, len); the user input will be displayed, followed by the mask placeholders that are still needed to complete correct input.
I have also added a user message in the .bind. This works for us, as we are using the MaskedInput for exactly one type of input. I'm checking for any input going further than position 7, because that's where the user input starts.
Here is what I did:
.bind("blur.mask", function() {
// find out at which position the checkVal took place
var pos = checkVal();
// if there was no input, ignore
if (pos <=7) {input.val(""); clearBuffer(0, len);}
// if the user started to input something, which is not complete, issue an alert
if (pos > 7 && pos < partialPosition) alert("Tell the user what he needs to do.");
if (input.val() != focusText)
input.change();
})
Adding Placeholder could solve the problem.
$(control).mask('999-999-9999');
Add an empty place holder into mask. see below
$(control).mask('999-999-9999', { placeholder: "" });
which would replace _ on the input text field by default. so there would bot be any _ left if the input length is dynamic and not fixed.
Looking for into the pluging script the unmask method.
$('#checkbox').unmask();

Categories

Resources