i am new to java script, so i had a doubt. i have created a form with username and password,i need to know how to change the background color of the text box on click? it will be helpful.
My code:
<script type="text/javascript">
function AllowLock(){
if (!locker.lock.value.match(/[a-zA-Z]$/) && locker.lock.value !="")
{
locker.lock.value="";
alert("Please Enter only valid lock");
}
if(locker.lock.value.length > 5)
alert("max length exceeded");
}
function AllowKey(){
if (!locker.keys.value.match(/[a-zA-Z]$/) && !locker.keys.value.match(/[0-9]+$/))
{
locker.keys.value="";
alert("Please Enter only valid key");
}
if(locker.keys.value.length > 5)
alert("max length exceeded");
}
function LockName(){
{
if(locker.lock.value.length==0)
document.getElementById('errfn').innerHTML="this is invalid name";
}
{
if(locker.keys.value.length==0)
document.getElementById('error').innerHTML="this is invalid key";
}
}
</script>
If you want to change the background-color while the input is focused (the caret is inside the input and the user is interacting with it there's no need for JavaScript, you can use CSS:
input:focus {
background-color: #ffa;
}
JS Fiddle demo.
With JavaScript, however:
var el = document.getElementById('inputElementID');
el.style.backgroundColor = '#ffa';
add this to you button's onclick function.
document.getElementById('error').style.backgroundColor="#some hex value";
Instead of on click, using focus would be better.
Use jquery for this.
Jquery looks different than javascript but it built with javascript. Just include jquery form the google CDN. Or download it and simply include it in your file.
$( "#divName" ).focus(function() { //give the div a name, and wrap the div around the text box
$(this).css( "background", "red" );
});
EDIT: OH yeah! The guy is right! There is totally a pseudo class for that. ( A CSS trick that takes care of it)
you don't need any JavaScript if you just want to change background color in input boxes
just use the CSS :focus pseudo-class.
input:focus{
background: #ffff00;
}
Check out this page to learn more about CSS pseudo-classes - http://www.tutorialrepublic.com/css-tutorial/css-pseudo-classes.php
I think is something like this:
<script>
window.onload="myFunction(
var textbox = document.getElementById('elementID');
textbox.onclick = changeColor;
function changeColor() {
textbox.style.backgroundColor = "#000000";
return false;
}
)";
</script>
Try using jQuery for this. It's much easier
$('#lock').click({
var input = $('#input').val();
var regex = '/[a-zA-Z]$/';
if(input != ''
&& !input.match(regex))
{
input.val('');
alert("Please Enter only valid lock");
}
if(input.length > 5)
{
alert("max length exceeded");
}
//Here is the CSS part. You can change it of the button or the input field
$('#input').css('background-color', 'red');
});
And here is the accompanying sample HTML. Also, the maxlength attribute that can be applied to certain inputs may kind of make your "max length exceeded" function kind of unnecessary.
<input id="input" value="" type="text" maxlength="5" />
<button id="lock">Lock</button>
CSS
Dont need JavaScript for that, Just add this style -
If you have some id assigned, Then using id error -
/* if your text box id is error */
#error:focus{
background-color: #ff0000;/* red some color*/
}
else you always can use other css selectors too, for example by tagname
/* for input tags */
input:focus{
background-color: #ff0000;/* red some color*/
}
Or by class
/* for `some-class` */
.some-class:focus{
background-color: #ff0000;/* red some color*/
}
JavaScript
If you want to use JavaScript then -
/* assuming your input element has id - `error` */
var el = document.getElementById("error");
/* add a click listener to it */
el.onclick = function() {
el.style.backgroundColor = "#ff0000";
}
Note
Using css way is better than JavaScript because its clean, and element-selector:focus will automatically take care of setting the previous background color when you click outside the input.
Related
JS Fiddle: https://jsfiddle.net/bcon865y/5/
Sorry if this is a little vague..
Trying to create a javascript form which validates each field using a onblur function once a field gets tested as correct the background of the field will turn green.
The submit button has a function which if all fields are green it will submit the form, however all fields are green but the form is not passing validation. I have no idea why this is happening any insight would be greatly appreciated, Hope i explained it well enough.
Below is the function in question, view the js fiddle to get the full context.
function validate() {
// Gets all the elements in the form with id="form1"
var elements = document.getElementById("form1").elements;
// loops through all elements in the form
for (var i = 0, element; element = elements[i++];) {
// Checks if the element in the form is either <input> or <select> && not green
if ((element =='[object HTMLInputElement]' || element == '[object HTMLSelectElement]') && (element.style.backgroundColor !='rgb(204,255,204)')) {
if (element.type!='color' && element.type!='submit') {
alert("Please enter data for any fields that are not green");
return false;
}
}
}
// to test the color picker
if (document.getElementById("color").value !='#000000') {
alert("please select a colour from the colour picker");
document.getElementById("The ID for your color picker goes here").focus();
return false;
}
}
It seems you're looking for a combination of the pattern field (on the input element) and the :valid & :invalid pseudo css selectors.
input[type="text"]:valid {
background: #BCED91;
}
input[type="text"]:invalid {
background: #F08080;
}
<form>
<input type="text"
id="name"
name="name"
required
pattern="[01]+">
<input type="submit">
</form>
The example above colors any text fields red if their values doesn't match the regex [01]+, and green if they do match it.
You can read more about form validation here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
What I'm going after is a code that will gather all my text input fields and detect whether or not they have any input. If so I'd like for there to be a glow effect added, if they're left empty or they delete the data and leave it empty I'd like for the glow effect to turn off.
So far from everything I've found this is what I came up with so far, it doesn't work of course, but it's the best I could try to rationalize.
function glow(){
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
if (text.value ==null){
text.style.boxShadow="#8fd7d2 0px 0px 22px";
}
else
remove.style.boxShadow;
}/**function**/
I used the .getElementsByClassName because the getElementsById didn't support multiple IDs as it seems, but if there's another more efficient way of gathering them all please share.
Simple solution can be adding class having glow with javascript:
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
text[0].className = text[0].className + " glow";
DEMO
Note: If you want to add glow class to each input then you have to iterate through loop and add class to each element. Because text is
HTMLCollection of elements.
You need to get the value of each element, not of the HTMLCollection returned by document.getElementsByClassName; Array.prototype.forEach can help with this. Then, a value can’t be null, but empty.
Edit: Wait a minute… you want the glow effect if the element has an input, right? Then your if-else statement is the wrong way around.
This is the correct function:
function glow() {
"use strict";
Array.prototype.slice.call(document.getElementsByClassName("tex_inp01 tex_inp02")).forEach(function(a) {
if (a.value !== "") {
a.style.boxShadow = "0px 0px 22px #8fd7d2";
}
else {
a.style.boxShadow = "";
}
});
}
You have a couple of mistakes in your existing code (as presented in the question): (1) text.value ==null - do not check against null, because an inputs value will never be a null. Check its length. (2) remove.style.boxShadow; - I think that was a typo. It should have been text.style.boxShadow = 'none'.
..to be a glow effect added, if they're left empty or they delete the
data and leave it empty I'd like for the glow effect to turn off..
You can check if the input has been left empty by simply checking the length of the value. However, to check if the input has been entered and then deleted you will have to keep a flag to keep track of that. You can do that by hooking up the change event on inputs and then setting a flag via data attribute. Later when you are checking each input for applying a style, along with the length also check this attribute to see if the input was edited out.
Here is a simple example putting together all of the above (explanation in code comments):
var inputs = document.getElementsByClassName("a b"), // returns a collection of nodelist
button = document.getElementById("btn"); // just for the demo
button.addEventListener("click", checkInputs); // handle click event on button
[].forEach.call(inputs, function(elem) { // iterate over all selected inputs
elem.addEventListener("change", function() { // handle change event
this.setAttribute("data-dirty", true); // set a data attribute to track..
}); // .. a flag when it is changed
});
function checkInputs() {
[].forEach.call(inputs, function(elem) { // iterate over selected inputs
var isDirty = elem.getAttribute("data-dirty"); // check the dirty flag we set
if ((elem.value.length > 0) || (isDirty)) { // if empty or changed
elem.style.boxShadow = "none"; // reset the style
} else {
elem.style.boxShadow = "#f00 0px 0px 5px"; // else apply shadow
}
});
}
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<button id="btn">Check</button>
If you wanted to validate the inputs while the user is typing, you can use keyboard events to check the value of the input(s):
document.querySelector('input[type="text"]').addEventListener('keyup',
function(event){
var element = event.target;
if (element.value.trim() === '') {
element.classList.add('empty');
} else {
element.classList.remove('empty');
}
});
See fiddle for example: http://jsfiddle.net/LrpddL0q/.
Otherwise this could be implemented the same way without the addEventListener to perform as a one-off function.
Jquery can help you as the following
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$(".MyInput").bind('keypress', function () {
$('.MyInput').css("boxShadow", "#8fd7d2 0px 0px 22px");
});
$(".MyInput").bind('keydown', function () {
if ($(".MyInput").val() == "") {
$('.MyInput').css("boxShadow", "none");
}
});
});
</script>
HTML:
<input type="text" value="" class="MyInput" />
this code working only online If you need to download Jquery library visit this
https://jquery.com/download/
The application creates a temp HTML Page for Print Version.
I can disable everything on the page so that user can not interact with the page..but that makes evrything grey in color and user is having problem with reading. SO i want to make everything to be readonly..
Here is my piece of code,
var x = 0;
var element;
while (x < document.getElementsByTagName("input").length) {
element = document.getElementsByTagName("input")[x].type
if (element = "BUTTON") {
document.getElementsByTagName("input")[x].onclick = null;
}
if (element = "TEXT") {
document.getElementsByTagName("input")[x].readOnly = true;
}
if (element = "CHECKBOX") {
document.getElementsByTagName("input")[x].disabled = true;
}
x++;
}
if i remove the if block for checkbox it is working fine. but if i include the checkbox condition it is making everything disabled(even buttons and text)..when i debug i see all the if blocks are executing.. i do not understand why.
Can some one plz help me out in this regard?
When checking for equality, use === right now you're using the assignment operator, =, which means every check will return true.
to compare use == instead of =
if (element == "BUTTON") { }
Use == instead of = inside if condition.
If you simple want to disable everything on the page - a faster way to do it is place transparent DIV over page content with z-index of a higher value.
Something like this:
Hello: <input type="text"/> <br>
Check this: <input type="checkbox" />
<div style="position: absolute; z-index: 10; top:0; left;0; width:100%; height:100%" />
Demo: http://jsfiddle.net/j39Au/
I think the differential styling for disabled inputs is useful because it provides a visual feedback for the user.
This doesn't address your question directly but it may be a good alternative. You could apply styling to the disabled inputs to suit your preference, maybe something like this.
input[disabled=disabled] {
background: rgba(255,0,0,0.05);
border: dashed 1px rgba(255,0,0,0.1);
color: black;
cursor: not-allowed;
}
Finally I made a workaround to this issue.
I converted all my elements(hyperlinks, dropdowns, text) to labels and displayed them in black color.
I would like to know how to write the javascript to alter the style of form elements which are required; and change them if they have values in them.
What I want to do is have a colored border around the required text fields when they are blank, and remove the border style when they have values.
what I've thought of doing is to write a single javascript function which checks if the value is empty and set the appropriate style:
function requiredElement(id) {
var Input = document.getElementById(id);
if(Input.value==null) {
Input.style.border = '2px solid #FF0000';
}
}
But what I'm stuck with is changing the style as user enters/removes characters in these required fields, and calling the function for the fields.
I have a simple html form, each input has a unique ID.
Use jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then add this code:
$('.important').change(function() {
if(($(this).val()) != '') $(this).css( 'border-width', '0' );
else $(this).css( 'border-width', '2' );
});
Assuming you added a border in the css
.important
{
border-style:solid;
border-width:2px;
border-color:red;
}
To determine when the element's value changes, bind your custom function to the onchange and onkeypress events (or, in jQuery, bind to .change() and .keypress()).
To actually change the appearance of the element, It's best to define styles in a CSS class and use JavaScript to add/remove the class as appropriate.
You can change an HTML element's CSS classes through JavaScript like this:
element = document.getElementById("myElement");
element.className = "invalid";
Or, in jQuery, use the .addClass() function:
$("#myElement").addClass("invalid");
HTML:
<input id="something" name="something" type="text" class="inputClass"
onchange="requireElement(this)"
onkeypress="requireElement(this)" />
JavaScript:
function requireElement(element) {
if(element.value == null)
element.className = "inputClass invalid";
else
element.className = "inputClass";
}
https://auth.me.com/authenticate
On this website when you type in your email address , the font-size will automatically be reduced if the email address fills the box size.
How can we do the same using Javascript?
which are the events that are being fired / captured ?
$("input").keypress(function(){
if(this.value.length>43)//or some other value
{//do stuff here
}
});
Keydown is what you are looking for
I have made a library, named resize.js, which allow to write:
<input type="text" resize="true" />
This is the library:
var precision=18;
window.onload=function()
{
for(var i=0,t=document.getElementsByTagName("input"),l=t.length;i<l;i++)if(t[i].getAttribute("resize")==="true")
{
var div=document.createElement("div");
div.setAttribute("style","font-size"+parseInt(t[i].s("font-size"))+";font-family:"+t[i].s("font-family")+";position:absolute;top:-10000px;left:-10000px;");
document.body.appendChild(div);
(function(i,div,min,max,dif,l,r,w,h,pre){setInterval(function(){modify(t[i],div,min,max,dif,l,r,w,h,pre);},100);})
(
i,
div,
t[i].getAttribute("min")||parseInt(t[i].s("font-size"))-3,
t[i].getAttribute("max")||parseInt(t[i].s("font-size")),
parseInt(t[i].s("padding-left"))+parseInt(t[i].s("padding-right"))+parseInt(t[i].s("border-left-width"))+parseInt(t[i].s("border-right-width"))+precision,
parseInt(t[i].s("padding-left")),
parseInt(t[i].s("padding-right")),
t[i].offsetWidth,
t[i].offsetHeight,
precision
);
}
}
Object.prototype.s=function(p)
{
return this.currentStyle?this.currentStyle[p]:document.defaultView.getComputedStyle(this,null).getPropertyValue(p);
}
function modify(el,c,min,max,dif,l,r,w,h,pre)
{
el.style.width=w+"px";
el.style.height=h+"px";
c.innerHTML=el.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/ /g," ");
var test=c.offsetWidth;
while(test>=el.offsetWidth-dif&&parseInt(el.s("font-size"))>min)
{
el.style.fontSize=parseInt(el.s("font-size"))-1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
while(test<el.offsetWidth-dif&&parseInt(el.s("font-size"))<max)
{
el.style.fontSize=parseInt(el.s("font-size"))+1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
if(parseInt(el.s("font-size"))===min&&c.offsetWidth>el.offsetWidth-dif)
{
el.style.paddingLeft="0px";
el.style.paddingRight="0px";
}
else
{
el.style.paddingLeft=l+"px";
el.style.paddingRight=r+"px";
}
}
A fiddle: http://jsfiddle.net/mageek/GEp2y/1
Some advices:
If the attribute "resize" equals anything other than true, or is not set, the text-box will behave as a normal text-box.
You can set the maximum font-size and the minimum font-size allowed by setting the "max" and the "min" attributes. By default, the maximum is the current font-size and the minimum is 3 sizes smaller than the maximum.
I added something, like https://auth.me.com/authenticate, which removes the padding to gain space when the minimum font-size is reached.
There is the variable 'precision' (at the beginning of resize.js) that depends on the text-box, I set it to 18 for default text-box but if you modify the style of the text-box, you will maybe have to modify the variable to a better value (by testing).
I don't ensure the host of resize.js on the website like in the fiddle, you should copy the source code in a new file and save it.
I've made the code for you, I took for example what I did on my own website for the contact form: the <textarea> gets taller if there is lot's of text.
The thing to do is to create an invisible<div>, for each keydown in the <input>, take its content and puts it into the <div>, and check its width is bigger than the <input>'s one.
The HTML
<form>
<input>
<div></div>
</form>
The CSS where we set the same font-size for the <input> and the <div> and hide the <div> (with position: absolute because we need it's width and we don't want it to change the layout)
form > * {
font-size: 22px
}
form > input {
width: 150px;
font-size: 18px;
}
form > div {
position: absolute;
left: -10000px;
}
And the JavaScript (with jQuery here)
var $form = $('form')
, $input = $('input', $form)
, $autoResize = $('div', $form)
, $both = $input.add($autoResize)
, fontSize = parseInt($input.css('font-size'), 10)
$input.on('keydown', function() {
$autoResize.html(this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ {2,}/g, function(spaces) {
// Change the spaces to $nbsp; except the last one
for (var i = 1, fakeSpaces = '', space; space = spaces[i++];) {
fakeSpaces += ' '
}
return fakeSpaces + ' '
})
)
// We add 10px to be sure it doesn't stick to the edges
if ($autoResize.outerWidth() >= $input.outerWidth() - 10) {
do {
$both.css('font-size', --fontSize)
} while ($autoResize.outerWidth() >= $input.outerWidth() && fontSize > 10)
// 10px is the smallest font-size accepted
if (fontSize === 10) {
$input.off('keydown')
}
}
})
Here is the jsFiddle.
You must use JavaScript to count how much characters've been typed already (I believe with .change() in jQuery) and change the font-size accordingly.
Yes,I think what #somebody is in trouble is doing is what they are doing in here.
Calculate how many letters will fit into the box - you know the width of the textbox. You know the font-size & padding that is being given here. So you know how many letters can be typed in the textbox before it overflows( not exactly) .
Or you can just type random letters & see how many can fit ! :)
Well, if you have time, you can as well dive into the events being fired when you keydown on the email address text box. You will learn a lot!