How to set cursor to input box in Javascript? - javascript

document.getElementById(frmObj.id).value="";
document.getElementById(frmObj.id).autofocus;
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
In the above code the value of the form object is perfectly setting to "" but there is no cursor in the text box. I want a cursor to be there. focus() only focuses that input box but does not actually set the cursor.

In JavaScript first focus on the control and then select the control to display the cursor on texbox...
document.getElementById(frmObj.id).focus();
document.getElementById(frmObj.id).select();
or by using jQuery
$("#textboxID").focus();

I realize that this is quite and old question, but I have a 'stupid' solution to a similar problem which maybe could help someone.
I experienced the same problem with a text box which shown as selected (by the Focus method in JQuery), but did not take the cursor in.
The fact is that I had the Debugger window open to see what is happening and THAT window was stealing the focus. The solution is banally simple: just close the Debugger and everything is fine...1 hour spent in testing!

Sometimes you do get focus but no cursor in a text field. In this case you would do this:
document.getElementById(frmObj.id).select();

One of the things that can bite you is if you are using .onmousedown as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup and viola, now focus() works, because the mouse is in an un-clicked state when the attempt to change focus is made.

This way sets the focus and cursor to the end of your input:
div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");

Inside the input tag you can add autoFocus={true} for anyone using jsx/react.
<input
type="email"
name="email"
onChange={e => setEmail(e.target.value)}
value={email}
placeholder={"Email..."}
autoFocus={true}
/>

You have not provided enough code to help
You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.
Here is the canonical plain javascript method of validating a form
It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point:
function validate(formObj) {
document.getElementById("errorMsg").innerHTML = "";
var quantity = formObj.quantity;
if (isNaN(quantity)) {
quantity.value = "";
quantity.focus();
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
return false;
}
return true; // allow submit
}
#errorMsg { color:red }
<form onsubmit="return validate(this)">
<input type="text" name="quantity" value="" />
<input type="submit" />
</form>
<span id="errorMsg"></span>

In my experience
document.getElementById(frmObj.id).focus();
is good on a browser running on a PC.
But on mobile if you want the keyboard to show up so the user can input directly then you also need:
document.getElementById(frmObj.id).select();

Related

Angular 6 Reactive Form Input Value to UpperCase

I am using Reactive form in Angular 6. For input type text I want it to be uppercase. I tried the solution
(input)="form.patchValue({name: $event.target.value.toUpperCase()})"
The solution works fine, but the only problem when I move cursor to middle and type a character, the cursor moves at the end.
Is there any other approach or any better solution?
why don't you just use CSS to do the job?
.uppercase{
text-transform: uppercase;
}
<input class="uppercase" type="text" placeholder="type here">
You can try this:
const yourControl = this.form.get('yourControlName');
yourControl.valueChanges.subscribe(() => {
yourControl.patchValue(yourControl.value.toUpperCase(), {emitEvent: false});
});
I know this is reeeeally late, but...
You could hook on to the (change) event instead of the (input) event. Your case changes won't execute until after the user leaves the field, but it will prevent the cursor from jumping.
You case changes will still execute if the user submits the form by pressing Enter while in the field.

Input value returns an empty string due to input font-size="0"

I found a problem which has bothered me for several weeks. I am using jQuery to retrieve the input text. The user enters some characters and hits ENTER, and I print the text in console.
html:
<input id="abc" type="text" autofocus style="font-size:0;">
jQuery:
$(document).on('keypress', '#abc', function(e) {
if (e.which!=13) {
return;
}
console.log('Entered: ' + $('#abc').val());
$('#abc').val('');
});
If I use Firefox, everything is fine. However, if I use Chrome or Opera, they will return a empty string.
I finally found out that the problem comes from font-size="0" (I want to hide the input). If the value is anything other than 0, Chrome and Opera will have no problem picking up the entered text.
Questions:
Why is that?
How do I hide the <input> element and it can still take user inputs?
To answer your second question, you can use CSS styles such as text-indent.
The text will be hidden offscreen and you'll stilll be able to get the value.
<input id="abc" type="text" autofocus style="text-indent:-9999em;">
I do believe that there are other ways to achieve this... like positioning the input offscreen
<input id="abc" type="text" autofocus style="position:absolute; left:-9999em; top:-9999em">
but your project seems pretty specific.

Clear password field

<input name="e_password" id="e_password" type="password" autocomplete="off" />
The above is a password field which for some reason, is automatically filled only in Mozilla (not in Chrome and IE11). Obviously it keeps the value field from previous trials. I tried so much to clear this field. The only way I can manage it, is through the following:
$(document).ready(function(){
$('input:text').val('');
});
Unfortunately, the above resets all the other text fields inside the form which is undesirable. Also,
$(document).ready(function(){
$('input:password').val('');
});
does not work!
Moreover, I tried this:
<div class="abc">
<input name="e_password" id="e_password" type="password" autocomplete="off" />
</div>
$(document).ready(function(){
$('.abc input:text').val('');
});
Nor, this works...
Of course, I tried the obvious:
$('#e_password').val('');
which also did not work.
I repeat that the problem exists only in Mozilla. What else may I do?
Thank you
document.getElementById("e_password").value = "";
or
$('input[type="password"]#e_password').val('');
I found it!!
setTimeout(function(){ $('#e_password').val('');}, 50);
Hopefully, the above works. However, I cannot give a satisfactory explanation why this small delay solves the problem...Most probably, it is a Mozilla bug.
Chrome ignore autocomplete="off"
Use autocomplete="new-password" in input
<input type="password" autocomplete="new-password">
https://bugs.chromium.org/p/chromium/issues/detail?id=587466
$("#e_password").val('') works for me in firefox. Can you try with this ?
$("#e_password").attr("value","")
Pure Javascript:
document.getElementById('e_password').value = '';
Or using jQuery:
$('#e_password').attr('value','');
autocomplete="off" must be set for form element not input
<form autocomplete="off">
....
</form>
I may be wrong but I guess it is not a code problem at all !!. It may be the saved passwords in the browser. For example when you open up the page in chrome , just check out the top right of the omnibox and you can click the cross to delete the saved password for that page. I guessed this because you say it comes only in mozilla and not other browsers.
This is an old question, but I did it a way that is not mentioned yet. This was after trying almost all suggestions in this thread (except the timeout as I don't want to add any unnecessary delays in my page).
The problem I saw was when the browser autofilled the password field, the value is not being set. So
$('#password').val("");
will not work, because the value is already "".
So I did it in 2 lines.
$('#password').val("a");
$('#password').val("");
I set the value to something so I could clear it out. Then the browser autofill field is cleared.
Hope this helps someone out there!
FF is using "change" event when auto-filling (at least in v51).
try something like
// if your input is in html
$(document).ready(function(){
/* // if you create input from code like this
$("body").html('<input class="password" type="password" id="e_password">').promise().done(function(){
*/
$("#e_password").on("change", function() { //append this event
$("#e_password").off("change"); //optional, depends on your code
$("#e_password").val(''); //clear
$("#e_password").attr("value",""); //clear #2 (just to be sure)
});
});
Chrome ignore autocomplete="off"
Use autocomplete="new-password" in input

jQuery: password field with readable label?

I wrote this very simple function for my current project called insidelabel() that let's me add a description (label) for an input field inside of the input.
//Label inside of inputfields
function insidelabel(selector, name) {
$(selector).val(name);
$(selector).css({'color':'#999'});
$(selector).focus(function () {
//Input Value
if ($(this).val() == name) { $(this).val(''); }
$(this).css({'color':'#000'})
});
$(selector).blur(function () {
if ($(this).val() == '') { $(this).val(name); }
if ($(this).val() == name) {
$(this).css({'color':'#999'});
}
});
}
insidelabel('.t', 'name');
insidelabel('.p', 'enter password');
So when an input is focused the text disappears and when it blurs it has the same text again.
<form method="get" action="">
<input type="text" class="t" value="" /><br/>
<input type="password" class="p" value="" />
</form>
However now I wonder how I could extend that function to have a label inside of password fields as well! Sounds weird... Explanation: I want a password field (with type="password") to have a readable label (like "enter password") inside of it. Once the user enters text the password should be unreadable (dotted). Really bad explanation, I know, but I think you might get what I mean.
I wonder what's the best way to do that? Should I query if an input field is type="password" and if so I set it to type="text" - once text is entered I set it back to type="password" again. Any idea what's the best solution for that?
Here is my example: http://jsfiddle.net/R8Zxu/
If you use a real <label> positioned under the (transparent) <input> instead of faking it with the value attribute (which has some major accessibility implications) then you can do something like: http://dorward.me.uk/tmp/label-work/example.html
Don't try to change the type of an existing input. Internet Explorer won't let you.
OK for web applications, but if you want to use page on iPhone application then it does not works properly, for correct answer see refer this - http://blog.stannard.net.au/2011/01/07/creating-a-form-with-labels-inside-text-fields-using-jquery/
Yes, that would be the right approach. This is known as a 'watermark' on a text field, and since password input fields use a different text display mechanism, when the watermark is active, you would want to switch it to a text type. OnFocus, you would switch it out (and if needed) focus on the new text field.
Just remember, you'll want to do the conversion to a type="text" before messing with the value; there are restrictions when it is a type="password".

Is there anyway to disable the client-side validation for dojo date text box?

In my example below I'm using a dijit.form.DateTextBox:
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying The value entered is not valid.. Even if I remove the constraints="{datePattern:'MM/dd/yyyy'}" it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.
Try overriding the validate method in your markup.
This will work (just tested):
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.
I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.
My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:
enableValidator:function() {
this.validatorOn = true;
},
disableValidator: function() {
this.validatorOn = false;
},
Then -- in the validator:function() I added a single check:
if (this.validatorOn)
{ ... }
Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:
http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js

Categories

Resources