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".
Related
I have a form as shown in the fiddle https://jsfiddle.net/vrn7zx5h/3/ in which I want to show the warning sign "Please fill out this field" at the same time for all unfilled required fields.
I found the answer on SO (as shown below) but i am not sure how to integrate with the fiddle.
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
Problem Statement:
I am wondering what changes I should make in the fiddle so that the above pasted SO answer works with the fiddle.
Here is a JS fiddle that will show all error at one time. It is just barebone and not fancy. You'll need to make it fancy on your own. I also disabled the built-in validator as well with novalidate in the form tag.
https://jsfiddle.net/6kxc9hmq/1/
FYI: I also did not put in the functionality to hide the error message on next run, if the input now satisfies the condition.
Basically, I attached a submit event handler to the form and if the validator returned false, I told the form to not submit. Works only on IE9+ (I think) all the other browsers are usually fine with this method. The validator is basically just checking if the value of the input met the condition that I specified.
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
I think it should look like this, if I understand what you mean
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
In your form, add empty divs after each input element. And you can conditionally display messages in the div in your validation. E.g if(name ==‘ ‘){div.innerHTML = ‘please enter your name’}
The required Attribute
Add the required attribute to your form.
The required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted.
I have a form with an input such as
<td class="units_depth_form">
<input id="id_form-0-rain" name="form-0-rain" step="0.01" type="number" />
</td>
and I want to allow a user to enter units. For instance the form could expect values in inches, but I would allow a user to enter '20 cm', and when leaving the text box it would contain '7.87'.
To do this I have in the JavaScript part of the page the following jQuery code:
$(".units_temp_form input").focusout(function() {
// Convert and replace if valid double ending with 'cm'
and I added 'novalidate' at the end of the form tag. The problem is that $(this).val() is empty when the input is invalid. Is there another way to get to the user entered value?
Before anyone suggests the solution, removing the type='number' part would solve the problem but I'd prefer not to do this. This form is created in Django through a ModelForm, and it would involve a lot of hacking that would defeat the purpose of using Django in the first place.
That seems to be the way browsers behave when they find invalid data inside a type="number" input.
Perhaps your best option is to use <input type="text"/> and implement the up and down arrows yourself. There are several options around, I found one that looks nice and another that keeps going on mouse down.
If the form inputs must be created with type="number" because of Django, you can change that on the client as soon as the page loads:
$(document).ready(function() {
$(".units_temp_form input").each(function(){
if ($(this).attr('type') == "number") {
$(this).attr('type', 'text');
}
});
});
I'm trying to deal with a frustrating Internet Explorer issue that prevents me from using jquery-validate in conjunction with jquery-placeholder. In short, the validation does not work on fields with type=password.
More info Here
One possible fix I came up with is to modify my passwords to be type=text, but this of course displays the passwords in plain-text rather than as *******.
Is there any clever html/js/css trick to make text fields display as though they were passwords?
So potentially you could have something set up like this.
Have a hidden input type that simulates the password values
So I guess jquery wise it would be
//everytime the password changes hidden changes with it.
$('#passwordId').change(function() {
$('#hiddenID').val() = $('#passwordId').val();
});
html:
<input type="password" id="passwordId" />
<input type="hidden" id="hiddenID" />
So this would allow you to validate the hidden input which would be the same value as the password.
First "hack" I can think of would be to add a "data-changed" attribute to the input="password" field, then attach an "onchange" event to the password field that sets "data-changed" == true, so that way you can validate if the value "password" was in fact entered by the user (data-changed == true) or if it is being submitted by the placeholder plugin itself.
While these answers were coming in, I had an epiphany of my own. At first glance, it appears to work. I'll check out the other answers and accept whichever approach looks like it will work best and be the least "hacky".
I came up with this approach when I discovered that the problem only exists when the field is empty (still has placeholder text), and as such, only will not pass "required" validation. My fix is to change it to type=password when content is entered.
My approach:
$('#password, #password_confirm').keyup(function(){
if ($(this).attr('type') === 'text') {
if ($(this).val().length > 0) {
$(this).attr('type', 'password');
}
} else if ($(this).val() == "") {
$(this).attr('type', 'text');
}
});
I am working on a login with a simple email-field and password-field.
I have all the basics of what I want but I can't put them all together.
What I want is the same look of the TEXT FIELDS as twitter.
What I mean by that is when the two fields aren't selected they say "Email" and "Password"
But when they are selected the text is unselectable and the cursor appears in the front.
As soon as you type they disappear and whatever you type appears.
The easiest solution is just adding a background image to them.
I have done this but do not want this look. Its not precise enough for me.
If you are confused with what I am looking for go to twitter and look at their LOG IN fields where they say username/password. I want that same look. Any help is GREATLY appreciated.
Thank You.
Please given in HTML, CSS or JavaScript if possible but any solution is appreciated.
<script type="text/javascript">
function clearInput(this) {
var currValue = document.getElementById(this).value;
if (currValue != '') {
currValue = '';
}
}
</script>
<input type="text" id="login" value="email" class="input-box" onchange="clearInput(this);">
<input type="password" id="password" value="password" class="input-box" onchange="clearInput(this);">
This is not tested by should work....
You can use any number of JS events so you will have to shoose the one which gives the timings you want.
Hope this helps.
Try using placeholder="your placeholder" on the inputs?
then you can use fall back jquery scripts to provide the functionality for older browsers
First, the javascript.... if you're using jQuery, this should take your text fields and remove the values in them (Email, etc) when click in them and bring them into focus.
$(function() {
$('input[type=text]').focus(function() {
$(this).val('');
});
});
Your html should look similar to this....
<input type="text" name="email" value="email"/>
<input type="password" name="password" value="password" />
To get the border highlight effect, you can add some css....note that this example will add a green border around all inputs (text fields, text areas, etc) when they are focused. You can change this by using id's or specifying the input type.
input:focus { border: 1px solid green;}
if you're trying to get the default text to disappear on keydown instead of on focus, one approach is to give each of the inputs an id, and then use a flag to check to see if the event handler (e.g the text disappearing) has already fired, on each of the ids...
$(function() {
var passFired = false;
var emailFired = false;
var email = $('#email');
var pass = $('#password');
email.keydown(function() {
if(!efired){
efired = true;
$(this).val('');
}
});
pass.keydown(function() {
if(!pfired){
pfired = true;
$(this).val('');
}
});
});
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();