Clear password field - javascript

<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

Related

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.

How to retrieve submit button with getElementsByTagName

I would like to get the a submit button using getElementsByTagName but I must be doing something wrong.
<p id="ptag">Want to find out if this works</p>
<button>The Button</button>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<input type="checkbox" name="yes" value="yes">A checkbox<br>
<input type="submit" value="Login">
</form>
in the above HTML snippet, If I use the below function, getting the button works yet getting the submit button does not.
window.onload = theFunction;
function theFunction(){
document.getElementsByTagName("BUTTON")[0].setAttribute("onclick", "theOtherFunction()");
document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");
}
What am I doing wrong?
function theOtherFunction(){
document.getElementById("ptag").style.color = "blue";
}
I added theOtherFunction() to my question because all my little experiment is doing is changing that <p> color to blue. With the button, it stays blue. With the submit button, it quickly turns blue and then goes back to black. What is the difference and how can I use the submit button to retain changes?
Take a look at your last line of code document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");
There is a ; you don't want there right after the [3].
Hope this helps.
jQuery becomes very useful here
$('input[type="submit"]')
This will allow you to make html changes with immunity and support older browsers that still have 1% usage.
Your 2nd example should work without the ; in the middle of the line. However not all browsers support getElementsByTagName.
Update using no ready made libs.
If you are a build it yourself person, who wants to make his own lib.
function getElementsByAttrib(attrib) {
return document.querySelectorAll('[' + attrib + ']');
}
var elements = getElementsByAttrib('type="submit"');
MySubmit = elements[0]';
It's not practical to target/retrieve specific input elements with getElementsByTagName.
We gotta use the right tool for the right job and in this case it's the query selector like this...
var S=document.querySelectorAll('input[type=submit]');
S[0].style.background='red'; // do something to the first button
NB: Code above assumes you only have one submit button or you'll have to loop through the array "S" to target all submit buttons.

jquery history of input select (easy)

I have an input field called email class keyup-an. I validate it easy with this, but it works or when an individual inputs the field manually. How do i make it work also for selecting historical data. when you click email and yesterday you put test#test.com, the history list drops down and you can select it, but its not a keyup.
I TRIED the same function after but with .change or .click and it didnt work. Can you guys please suggest?VALID
$('.keyup-an').keyup(function() {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Validationfail</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
you can do this by
autocomplete='off'
example
<form name="form1" id="form1" method="post" autocomplete="off">
or try something like
$(input).autocomplete().keyup(function(event) {
event.stopPropagation();
}).keydown(function() {
$(this).autocomplete('search', $(input).val());
});
good read
How to Turn Off Form Autocompletion
If I understand you correctly, you want an event which gets triggered if you click on the autocomplete item.
This is a known bug, check out this article about a jquery plugin, I think this is exactly what you need:
http://furrybrains.com/2009/01/02/capturing-autofill-as-a-change-event/
Instead of binding your function to the keyup event.. maybe bind it to change event?
ok.. this doesn't work on some browsers it seems.. you can refer to the previous answer and use the solution, which basically creates a timer to check the values in intervals to detect changes. Forcing the browser to do a lot of work if you want the validation to happen very fast imo.. Or you could turn of autocomplete and force the user to enter the values manually like the first answer suggested.

How to set cursor to input box in 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();

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