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
Related
So I have this problem where I want to mark the checkbox checked when the user input a certain value. For example when the user inputted "FAAS" the checkbox should be check. How to do this?
Here is my code:
HTML:
<input type="text" name="faashidden" id="faashidden">
<input id="faasfrontandback" name="faasfrontandback" type="checkbox">
<label for="faasfrontandback">FAAS Front & Back</label>
and when the user will input something in faashidden and click the button the checkbox should be checked. Here is my javascript code:
var faas = $("#faashidden").val();
if (faas.value == "FAAS") {
document.getElementById("faasfrontandback").checked = true;
}
Try this:
$("#faashidden").keypress(function(e){
var faas = $("#faashidden").val();
if (faas == "FAAS") {
$("#faasfrontandback").prop('checked', true);
}
});
It adds an event listener on the input. Every time the user hits a key while focused on the input, the function checks the content of the input and checks the box if it's "FAAS".
Edit: you may also want to check the box whether the input is "FAAS" or "faas". In that case, convert the input to lowercase and compare the result with "faas". See below:
$("#faashidden").keypress(function(e){
var faas = $("#faashidden").val().toLowerCase();
if (faas == "faas") {
$("#faasfrontandback").prop('checked', true);
}
});
I have taken a 70-480 Microsoft exam this morning(HTML5,CSS3 and Javascript), and I found one question to be confusing/wrong/incomplete. The question is this:
you have a checkbox input and a text input on the webpage.
<input type="checkbox" id="chkBox" />
<input type="email" id="txtEmail" disabled/>
The requirement is that, when a user checks the checkbox:
the email input should be enabled
when the user unchecks the checkbox
the email input should be disabled
the email input should have gray background
You have the following script and style defined:
<style>
(selector) {
background-color:gray;
}
</style>
<script>
var chkbox = document.getElementById("chkBox");
if(chkbox.Checked)
{
document.getElementById("txtEmail").(selector) = (selector);
}
else
{
document.getElementById("txtEmail").(selector) = (selector);
}
</script>
You can pick from the options given below to replace the (selector) in the above code. you can use the same option any number of times.
1)enabled
2)disabled
3)true
4)false
5)set
I know that for enabling and disabling I need to use option 2,3 and 4 as shown below. And for the other (selector) which is in CSS, I had no clue what option made sense there. It did not make any sense to me, do you guys think the question is wrong or incomplete?
if(chkbox.Checked)
{
document.getElementById("txtEmail").disabled = false;
}
else
{
document.getElementById("txtEmail").disabled = true;
}
There is an :disabled selector, but it should have specified a colon in front of it, in my opinion
http://www.w3schools.com/cssref/sel_enabled.asp
Please visit below link to select disabled input
https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
input[type="email"]:disabled {
background: #d3d3d3;
}
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/
I have the following example (simplified to help others) where an error class is added if fields don't meet basic validation requirements:
var email = $("input#email").val();
if (email == "") {
$("#emailblock").addClass("has-error")
var prevent = 1;
}
var org = $("input#organisation").val();
if (org == "") {
$("#orgblock").addClass("has-error")
var prevent = 1;
}
// if no entry, prevent submission and highlight first field
if (prevent == '1') {
$(".has-error:first").focus();
}
However, using the above code doesn't focus on the first instance of .has-error after using addClass().
How can you select the first instance of has-error or any other dynamically assigned class after using .addClass to a <div> that contains a form element?
You can only focus() on <input>, <select>, <a href> etc
change $(".has-error:first").focus(); to $(".has-error:first input").focus();
Here is a demo
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.