How to create a label inside an <input> element and style it? - javascript

I can make my label inside an input element (my "disappearing text"):
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" />
Then style it so my disappearing text is faded (#333). And style it so when I start to input a value into the field the text is black (#000).
CSS
input[type=text] {
color: #333;
}
input[type=text]:focus {
color: #000;
}
It all works fine until you move onto the next input field. Then the field you just entered a value in changes back to the #333 color. I can see why that happens, but can't quite get to how to keep the value black #000 color if the input field has had a value put into it.
Thanks in advance for the assist and education!

HTML5
HTML5 brings a handy attribute for the <input> tag called placeholder which enables native support of this functionality.
jsFiddle
<input type="text" placeholder="Search..." />
Support
All latest browsers support this, IE9 and below don't however.
<label>
Note that the placeholder attribute is not a replacemenr for the <label> tag which every input should have, make sure you include a label for the <input> even if it's not visible to the user.
<label for="search">Search</label>
<input id="search" placeholder="Search..." />
The above <label> can be hidden so it's still available to assistive technologies like so:
label[for=search] {
position:absolute;
left:-9999px;
top:-9999px;
}
Cross-browser solution
Here is a potential cross-browser solution, I've moved the code out of the tag and into script tags and then used the class placeholder to indicate when to fade the text.
jsFiddle
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
class="placeholder" id="my-input" />
CSS
input[type=text].placeholder {
color: #999;
}
JS
<script type="text/javascript">
var input = document.getElementById('my-input');
input.onfocus = function () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
};
input.onblur = function() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
};
</script>
Apply to all input[type=text]
We can extend the above solution to apply to all input[type=text] by using document.getElementsByTagName(), looping through them and checking the type attribute with element.getAttribute().
jsFiddle
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') === 'text') {
input[i].onfocus = inputOnfocus;
input[i].onblur = inputOnblur;
}
}
function inputOnfocus () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
}
function inputOnblur() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
}

This appears to work xbrowser using a combination of jQuery and the Modernizer library.
Requires the jQuery and Modernizer Libraries be on the site and properly referenced.
HTML
<head>
<script src="jquery-1.9.1.min.js"></script>
<script src="modernizr.js"></script>
<script>
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
</script>
</head>
<body>
<form>
<input name="firstName" type="text" maxlength="40" placeholder="Enter your first name">
</form>
CSS
input[type=text] {
color: #000;
}
input[type=text].placeholder {
color: #666;
}
SOURCE: http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text

Related

How to change background color of an input field with conditionals in JavaScript

I tried to change the background color of the input field with an if statement. I dont know why it isnt working. What can I do to get it working?
function increment() {
var textbox = document.
getElementById("inc");
textbox.value++;
}
var inputfield = document.getElementById("inc")
// trying to change bg color of inputfield if number higher or lower -- doesnt work yet
if (inputfield.value > 3) {
inputfield.style.backgroundColor = "#AA0000";
}
<div class = wrapper>
<button onclick="increment()">Click to + 1!</button>
<input class="inputfield" id="inc" type="text" value="0" />
</div>
While your javascript function increment() gets executed each click of the button, the rest of your javascript code gets only executed once after the document has been loaded. Initially input field #inc value is 0 and will not change color as it never becomes > 3 this way.
In your Javascript:
you only have to get the reference to input element #inc once (const textBox) and use that in your increment function. In the snippet I defined the constant textBox as global because the reference does not change, just its .value. Consequently method .getElementById does not have to be executed each click of the button.
After the button has been clicked, increment textBox.value and change the color when the value > 3.
Snippet
// Get a reference to the textbox
const textbox = document.getElementById("inc");
function increment() {
textbox.value++; // increment its value
if (textbox.value > 3) {
// change its color
textbox.style.backgroundColor = "#AA0000";
}
}
<div class=wrapper>
<button onclick="increment()">Click to + 1!</button>
<input class="inputfield" id="inc" type="text" value="0" />
</div>
Check this out.
const inputfield = document.getElementById("change_color_example")
inputfield.addEventListener("keyup", function() {
if (this.value > 3) {
this.classList.add("active-math")
} else {
this.classList.remove("active-math")
}
if (this.value.length > 3) {
this.classList.add("active-length")
} else {
this.classList.remove("active-length")
}
})
.example-input {
color: #333333;
background-color: #ffffff;
border: 1px solid #000000;
transition: all 300ms linear;
}
.example-input.active-math {
color: #f8f8f8;
background-color: #AA0000;
}
.example-input.active-length {
color: blue;
background-color: bisque;
}
<input type="text" id="change_color_example" class="example-input" />
We can start of by grabbing the input element from the DOM.
const input = document.querySelector('input');
Once we have the element to work with we can, we can add an event listener (blur) so whenever a user moves out of the box the action in the code will be performed.
JS:
const input = document.getElementById("input");
input.addEventListener("blur", () => {
if (input.value.length > 3) {
input.style.backgroundColor = "red";
}
});
HTML:
<input type="text" id="input" />

Simple Javascript client-side form validation

Goodmorning everyone,
I have a problem with a script for validating a form.
Given that the module has server-side validation in PHP, what I want to achieve, too, is client-side validation.
This validation is very simple.
When you click on the SUBMIT button, you must check if all the mandatory fields have been filled in.
If they are not:
must add a class to the input to make it change color;
must change the content of the icon next to the input field.
I use this script which works with regards to check and class on input. However, it uses a check on the NAME of the fields.
HTML
<form id="signinform" method="post" action="" class="wp-user-form" autocomplete="off" onsubmit="event.preventDefault(); validateMyForm();" novalidate>
<div class="msc-login-form-input">
<input type="text" name="log" value="" size="20" id="user_login" placeholder="Username o Email" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input">
<input type="password" name="pwd" value="" size="20" id="user_pass" placeholder="Password" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input-sendh">
<input type="submit" id="submit-login" name="submit-login" value="" class="user-submit" />
</div>
</form>
JS
<script lang="javascript">
function validateMyForm(){
let isFormValid = true;
let elems = document.getElementsByName("namefield");
for(let i=0; i< elems.length; i++)
{
let elem = elems[i];
if(elem.value.length < 1)
{
if(isFormValid){
isFormValid = false;
}
}
validateElement(elem);
}
if(isFormValid)
{
document.getElementById("signinform").submit();
return true;
}
}
function validateElement(elem){
if(elem.value.length < 1)
{
elem.className = "errorClass";
}else{
elem.className = "okClass";
}
}
</script>
CSS
<style>
.msc-login-form-input input.okClass {
background-color: #ffffff;
color: #3F4254;
}
.msc-login-form-input input.errorClass {
background-color: #4d40ff;
color: #ffffff;
}
.msc-login-form-input #errorsign {
width: 35px;
background-color: rgba(0,0,0,0.05);
min-height: 100%;
align-items: center;
justify-content: center;
text-align: center;
display: flex;
}
.msc-login-form-input #errorsign::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f100";
}
.msc-login-form-input #errorsign.fail::before {
content: "\f00d";
color:#4d40ff;
}
.msc-login-form-input #errorsign.okay::before {
content: "\f00c";
color:#FF1493;
}
</style>
The problem is that the NAMEs of my fields are not the same and therefore that loop cannot work.
How can I solve without duplicating the loop for each form field?
How can I also add the control on the class of the icon next to it?
Thank you.
If you don't want to use the builtin validation, I'd do it as follows
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
//this is the span element holding the icon
let icon = elements[i].getElementsByTagName("span")[0];
let valid = validateElement(input);
//set the classes input and span according to the validation result
input.classList.Add(valid ? "okClass" :"errorClass");
span.classList.Add(valid ? "okay" :"fail");
input.classList.Remove(valid ? "errorClass": "okClass");
span.classList.Remove(valid ? "fail" : "okay" );
//the form is only valid if ALL elements are valid
formvalid &= valid;
}
function validateElement(element) {
if (input.value.length === 0) return false;
//any other validations you want to do
return true;
}
Furhtermore you have a problem in your DOM tree. You have mutliple <span> elements with the same id="errorsign". That's not gonna work, because an id has to be unique. So remove the ids and grab the <spans> from their parents as shown above.
You could also just add the "okay" and "fail" to the surrounding <div> and adapt your css accordingly. Ie something like the following CSS
.msc-login-form-input.okay input {
...
}
.msc-login-form-input.fail input {
...
}
.msc-login-form-input.okay span::before {
...
}
.msc-login-form-input.fail span::before {
...
}
And the following JS
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
let valid = validateElement(input);
element.classList.Add(valid ? "okay" : "fail");
element.classList.Remove(valid ? "fail": "okay");
formvalid &= valid;
}

How to clear a text field on click and also change it's color

I have a search text box with an initial value of "Search" and a gray color.
When it is clicked, I want to clear the text and set the color to black so when the User stats typing, it is in black.
I have this so far and it clears fine. I tried to add a css style to it but its gives me a syntax error: the attribute is missing the attribute name following the namespace.
onfocus="if(this.value == 'Search') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Search'; }"
onfocus="if(this.value == 'Search') { this.value = ''; style="color: #000000;"; }" onblur="if(this.value == '') { this.value = 'Search'; }"
If you don't want to support IE9 and below then
You should use placeholder attribute with some CSS like
input::-webkit-input-placeholder { color: #555; }
input::-moz-placeholder { color: #555; }
input:-ms-input-placeholder { color: #555; }
input:-moz-placeholder { color: #555; }
<input type="text" placeholder="Search" />
The right way to set the color would be to change the color property on the style property of the DOM element, so something like
this.style.color = ...
So, if you want to support IE9 or something similar
<input onfocus="if (this.value == 'Search') { this.value = ''; this.style.color = '#000000'; }" onblur=" if (this.value == '') { this.value = 'Search'; this.style.color = 'red'; }" value="Search" style="color: red" />
Otherwise, Ankit's answer would be the right way to go

Javascript focus() not working when onkeyup event is executed in iOS

I have 4 input boxes to enter 4 digit passcode. I want to focus to the next input box when the first input box is filled by user.
I had to use document.getElementById('second').focus(); to focus to the next input box. Unfortunately this does not work in iOs.
I did further research and found that focusing is not happened with the event like "onkeyup", "onkeypress", but it works with "onclick" event.
Do you guys any idea to fix this problem or alternative solution to fix this problem.
HTML
<input id="first" name="first" type="number" style="width: 50px; height: 50px;" maxlength="1" onkeyup="focusSecondBox(event);" />
<input id="second" name="second" type="number" style="width: 50px; height: 50px;" maxlength="1" onkeyup="focusThirdBox(event);"/>
JS
function getEventCharCode(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return charCode;
}
function isEmptyElement(element){
return (element === null || element.value === null || element.value === '');
}
function focusSecondBox(evt){
var element = document.getElementById('first');
var previousElement = document.getElementById('first');
var nextElement = document.getElementById('second');
focusInput();
}
function focusInput(){
var charCode = getEventCharCode(evt);
if (isEmptyElement(element)) {
if (charCode === 8) {
previousElement.focus();
previousElement.value = previousElement.value;
}
} else if (nextElement !== null) {
nextElement.focus();
}
}
Thank you
In iOS safari. Difficult or impossible to show keyboard by call focus() without mouse event as far as I know.
alternative solution
But, in this case, I implemented what expect in the following ways:
Use invisible input field.
Focus invisible input field when any input passcode field focused.
Move invisible input field position with key event.
Change passcode field by invisible input field.
HTML
<div id="dummyDiv" style="width:0px;height:0px;overflow:hidden;">
<input id="dummy" type="number" />
</div>
<input id="p0" type="number" style="width: 50px; height: 50px;" maxlength="1" />
<input id="p1" type="number" style="width: 50px; height: 50px;" maxlength="1" />
<input id="p2" type="number" style="width: 50px; height: 50px;" maxlength="1" />
<input id="p3" type="number" style="width: 50px; height: 50px;" maxlength="1" />
JavaScript
window.addEventListener('load', function() {
var words = [];
for(var i=0; i < 4; i++) {
words[i] = document.getElementById('p'+i);
}
var dummy = document.getElementById('dummy');
var dummyDiv = document.getElementById('dummyDiv');
words.forEach(function(word) {
word.addEventListener('click', function(e) {
dummy.focus();
});
});
dummy.addEventListener('keypress', function(e) {
if (dummy.value.length >= 4 || !String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
e.preventDefault();
}
});
dummy.addEventListener('keyup', function(e) {
console.log(dummy.value);
var len = dummy.value.length;
for(var i=0; i<4; i++) {
if(len <= i) {
words[i].value = '';
} else {
words[i].value = dummy.value[i];
}
}
if (len>=4) {
return;
}
dummyDiv.style.position = 'absolute';
var rect = words[len].getBoundingClientRect();
dummyDiv.style.left = rect.left+'px';
dummyDiv.style.top = (rect.top+15)+'px';
});
});
working sample
http://nakaji-dayo.github.com/ios-safari-passcode-boxes/
Please look on iOS
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#hidebox {position:absolute; border: none; background:transparent;padding:1px;}
#hidebox:focus{outline: 0;}
</style>
</head>
<body>
<input type="text" maxlength="1" onkeyup="keyUp(this)" onkeydown="keyDown(this)" size="2" id="hidebox" at="1">
<input type="text" maxlength="1" size="2" id="mFirst" at="1" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mSecond" at="2" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mThird" at="3" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mFourth" at="4" onfocus="onFocus(this)">
</li>
<script type="text/javascript">
window.onload = function() {
document.getElementById("mFirst").focus();
}
var array = ["mFirst","mSecond","mThird","mFourth"];
function keyUp(e) {
var curId = array[Number(e.getAttribute("at"))-1];
var nextId = array[Number(e.getAttribute("at"))];
var curval= e.value;
var letters = /^[0-9a-zA-Z]+$/;
if(e.value.match(letters)){
document.getElementById(curId).value = curval;
if(e.getAttribute("at") <= 3){
var nextPos = document.getElementById(nextId).offsetLeft;
e.setAttribute("at",Number(e.getAttribute("at"))+1);
e.style.left = nextPos+"px";
}
e.value = ""
}else {
e.value = "";
}
}
function keyDown(e) {
var curId = array[Number(e.getAttribute("at"))-1];
document.getElementById(curId).value = "";
}
function onFocus(e) {
document.getElementById("hidebox").focus();
document.getElementById("hidebox").setAttribute("at",Number(e.getAttribute("at")));
document.getElementById("hidebox").style.left = e.offsetLeft+"px";
document.getElementById("hidebox").style.top = e.offsetTop+"px";
}
</script>
</body>
</html>

When text is entered correctly, image lights up/changes

I am building a section on my website for language learning. The user will see the word でんき (Japanese word). When someone enters in the correct text that matches each symbol, one of them will light up. How could I achieve this?
Here is a preview image of my site: http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
Here's an example with a normal input field:
<script type="text/javascript">
var answer = 'foo';
function checkMatch(val) {
if (val == answer) {
alert('CORRECT!');
}
}
</script>
<input type="text" id="word_box" value="" onkeyup="checkMatch(this.value)" />
This is incredibly simplified, but you get the idea. onkeyup will be called whenever a key is pressed in a box or other editable field.
Here's another one to add to the mix. Short answer is use Javascript, HTML, and CSS to accomplish this.
http://jsfiddle.net/BUxvx/1/
HTML
<span data-answer="cat" data-for="1">Symbol 1</span>
<span data-answer="dog" data-for="2">Symbol 2</span>
<span data-answer="chicken" data-for="3">Symbol 3</span>
<br />
<input type="text" data-for="1" />
<input type="text" data-for="2" />
<input type="text" data-for="3" />
< - Type answers here
<br />
<span>cat</span>
<span>dog</span>
<span>chicken</span>​
JavaScript
$('input').keyup(function(){
$txt = $(this);
$span = $('span[data-for="' + $txt.attr('data-for') + '"]');
if($(this).val() === $span.attr('data-answer')){
$span.addClass('highlight');
}else{
$span.removeClass('highlight');
}
}); ​
CSS
span{
display:inline-block;
height:75px;
width:75px;
line-height:75px;
text-align:center;
border:1px solid black;
}
input{
width:75px;
border:1px solid black;
}
.highlight{
background-color:yellow;
}
​
HTML
<div class="question">
<span data-answer="correctAnswerOne">で</span>
<span data-answer="correctAnswerTwo">ん</span>
<span data-answer="correctAnswerThree">き</span>
<div>
<label for="answer">Enter your Answer</label>
<input id="answer" />
Javascript
//Build an array of correct answers
var answerArray = "";
var i = 0;
$('.question span').each( function() {
answerArray[i] = this.attr('data-answer');
i++;
} );
//On key up, get user input
$('input').keyup(function(){
$('.question span').removeClass('highlight');
var userInput = $('#inputElementID');
var userInputArray = string.split(' ');//Split the string into an array based on spaces (I assume you are looking for three separate words
var answerCount = array.length;
for (i=0;answerCount >= i;i=i+1) {
if (userInputArray[i] == answerArray[i]) {
$('span[data-answer=' + answerArray[i] + ']').addClass('highlight');
}
}
});
CSS
.highlight{
background-color:yellow;
}
Here's a simple way:
<span data-value="Car">{character that means Car}</span>
<span data-value="Boat">{character that means Boat}</span>
<span data-value="Plane">{character that means Plane}</span>
<input>
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
$('[data-value="'+val+'"]').addClass('highlight');
});
Explanation:
The data-value will hold the English text of your character. When the user types a value that matches it, it will add the highlight class to all elements that have a data-value matching the text. Just apply your "lighting up" styles to the class.
Demo: http://jsfiddle.net/MTVtM/
To work with multiple words just split the value by a space and check each piece:
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
val.split(' ').forEach(function(v) {
$('[data-value="'+v+'"]').addClass('highlight');
});
});
Demo: http://jsfiddle.net/MTVtM/1/ (Try entering "Car Boat")

Categories