onBlur change textbox background color - javascript

How can i change my textbox background and border color if return true from the function ? if return false my textbox background border will change, but when return true it remain red color. how can i fix this ? any help will be appreciated.
Javascript
function checkPostcode()
{
var message = "";
if (document.mainform.POSTCODE.value.length != 5)
{
message += "Invalid entry. Postcode must be in 5 number.";
}
else
{
for (var i = 0; i < document.mainform.POSTCODE.value.length; i++)
{
var f = document.mainform.POSTCODE.value.charAt(i);
if (!(parseFloat(f) >= 0) || !(parseFloat(f) <= 9))
{
var jdap = "no";
}
}
if (jdap=="no")
{
message += "Invalid entry. Please enter numbers only.";
}
}
if (message != "")
{
document.getElementById("posterrMsg").innerHTML = message;
document.getElementById("posterrMsg").style.display = "inline";
document.getElementById("POSTCODE").style.border = "thin solid red";
document.getElementById("POSTCODE").style.background = "#FFCECE";
document.mainform.POSTCODE.value = "";
document.mainform.POSTCODE.focus();
return false;
}
else{
document.getElementById("posterrMsg").innerHTML = "";
document.getElementById("posterrMsg").style.display = "";
document.getElementById("POSTCODE").style.border = "thin solid #CCCCCCC";
document.getElementById("POSTCODE").style.background = "FFFFFF";
return true;
}
}
HTML
<label id="posterrMsg" class="errMsg"></label>
<input type="text" name="POSTCODE" id="POSTCODE" value="<%=POSTCODE%>" onblur="checkPostcode();" maxlength="5" />

Just change
document.getElementById("POSTCODE").style.border = "thin solid #CCCCCCC";
to
document.getElementById("POSTCODE").style.border = "";

Another option:
document.getElementById("POSTCODE").className = "validPostcode";
or
document.getElementById("POSTCODE").className = "invalidPostcode";
If you want to add more styling.
Both are valid options here.
I would refactor your code a bit and maybe create an outer function which calls checkPostcode for validation.

Use !== so
if (message !== "")
so that you are checking the same type and value.
You also had a couple of typeos in your background colours.
See working JSFiddle here

Related

Can you create a function to check multiple input values and change their style accordingly?

I am writing a form and I am trying to simplify my code into a function but cant figure it out.
This is javascript for a form filling out text inputs
is there a way to loop over all inputs to make sure they are filled and if one is not, change the style of that input box to a red color?
(not worried about the spans but if you have a solution I'm all ears, would also love to see a similar example)
but.addEventListener("click", () => {
if (firstname.value == "" || lastname.value == "") {
firstname.style.backgroundColor = "rgba(200,0,0,.4)";
lastname.style.backgroundColor = "rgba(200,0,0,.4)";
span.style.display = "block";
span.innerHTML = "Please enter a valid Name";
}
if (age.value == "" ){
span.style.display = "block";
age.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter your age";
} if (isNaN(age.value) == true ){
span.style.display = "block";
age.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter a valid Age";
} if (job.value == "") {
span.style.display = "block";
job.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter a role";
} if (email.value == "") {
span.style.display = "block";
email.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter an email";
} if (phone.value == "") {
span.style.display = "block";
phone.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter phone number";
}
})
I think this should do the trick for you, if you want to do it with a loop.
inputCollection is an array of all the elements which should be validated, which you pass into the function. The error span would be just the placeholder.
Personally i wouldn't add those styles via javascript and would use css for that matter.
function validateInputs(inputCollection, errorspan){
for(let i = 0; i < inputCollection.Length; i++){
let defaultValue = inputCollection[i].getAttribute('data-default');
let errorMessage = inputCollection[i].getAttribute('data-errormessage');
if(inputCollection[i].value === defaultValue || (!isNaN(defaultValue) && isNaN(inputCollection[i].value))){
errorspan.innerHTML += `${errorMessage}`;
}
}
}
i wrote this without validating the code but it should help you out.
Update 1
To your questions:
The data-default attribute should be the default value, so for example a empty string for the name, a number for the age ect.
The data-errormessage attribute from my first reply would contain the detailed message, so your assumption is correct.
Below you can find a snippet which should make the functionality more clearer
document.getElementsByTagName('button')[0].addEventListener('click', function(){
/*collection of all elements which should be validated*/
var col = document.querySelectorAll('input[data-default]');
for(let i = 0; i < col.length; i++){
let defaultValue = col[i].getAttribute('data-default');
if(col[i].value === defaultValue || (!isNaN(defaultValue) && isNaN(col[i].value))){
col[i].classList.add('hasError');
}else if(col[i].classList.contains('hasError')){
col[i].classList.remove('hasError');
}
}
});
.errormessage{
display: none;
}
.hasError{
background:#f00;
}
.hasError + span.errormessage{
display:block;
}
<form>
<div>
<input type='text' data-default="0" name='age' />
<span class='errormessage' >some error message for the age</span>
</div>
<div>
<input type='text' data-default="" name='name' />
<span class='errormessage' >some error message for the name</span>
</div>
</form>
<button>validate</button>

How to allow one specific word into text field in form using javascript?

I have input number field which is from 1000 to 10000 range but I also want to allow one only word 'All' into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks
<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>
Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don't need the isNaN function in there so if you want to remove it, the if statement will still work.
var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;
_input.addEventListener("input",function(){
var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));
if(!_valid){
var error = document.getElementById("error");
error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>
A number type can't have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.
const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
const val = e.target.value;
let showError = false;
if (isNaN(val)) {
if (val.toLowerCase() !== 'all') {
showError = true;
}
} else {
const numVal = +val;
if (val < 1000 || val > 10000) {
showError = true;
}
}
const errorElem = document.querySelector('#error');
if (showError) {
errorElem.innerText = 'Invalid; Value!';
} else {
errorElem.innerText = '';
}
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

document.getElementsByTagName is working but same functionality is not working with document.getElementById

I was trying to change the color of placeholder of input tag using Javascript. I am able to achieve that if I use document.getElementsByTagName, but if I am using document.getElementById then it's not working.
HTML:
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
JavaScript (with document.getElementsByTagName):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
JavaScript (with document.getElementById):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
I am not able to figure why this is happening.
getElementById returns only 1 element, it is not an array
function ChangePlaceHolderColorx() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += "Red";
}
}
}
}
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += "Red";
}
}
}
.Red{
color:red;
}
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
You have to change function ChangePlaceHolderColor() to:
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
this is because getElementByTagName() will return HTMLCollection which you can treat as an Array, but getElementById() will return only one element.
getElementsByTagName will always return an array of HTML elements, whereas getElementsById will always return a single HTML element.
function ChangePlaceHolderColor() {
//no loop because the return is one element.
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
In HTML, element IDs must be unique on any given page.

Validating a form

IM working on a simple form, and Im trying to validate the fields,
with below code I able to validate the field and add a message if the field is empty.
}
First you need to scan the page for labels:
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
Then you can simply use following in your IF-ELSE condition,
document.getElementById(id).label.classList.add('red-text');
and
document.getElementById(id).label.classList.remove('red-text');
I also added CSS class for the text to be red.
.red-text {
color: #ff0000;
}
Final code:
function validation(id) {
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById('Err' + id).innerHTML = "- Field Required";
document.getElementById(id).classList.add('class');
document.getElementById(id).label.classList.add('red-text');
} else {
document.getElementById('Err' + id).innerHTML = "";
document.getElementById(id).classList.remove('class');
document.getElementById(id).label.classList.remove('red-text');
}
}
.class {
background: #f97d7d;
color: #ff0000;
border: 1px solid #ff0000 !important;
}
.red-text {
color: #ff0000;
}
<label for="Name">* Name <span class="error" id="ErrName"></span></label>
<input type="text" name="Name" id="Name" onblur="validation('Name')">
Change your javascript code to following:
function validation(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById('Err' + id).innerHTML = "- Field Required";
document.getElementById(id).classList.add('class');
var label = findLabel(document.getElementById('Name'));
label.classList.add('class');
} else {
document.getElementById('Err' + id).innerHTML = "";
document.getElementById(id).classList.remove('class');
var label = findLabel(document.getElementById('Name'));
label.classList.remove('class');
}
}
function findLabel(el) {
var idVal = el.id;
labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor == idVal)
return labels[i];
}
}
.class
{
background: #f97d7d;
color: #ff0000;
border: 1px solid #ff0000 !important;
}
<label class="" for="Name">* Name <span class="error" id="ErrName"></span></label>
<input type="text" name="Name" id="Name" onblur="validation('Name')">
I've added a function findLable to get the label for that input, and using that, added error class to that label.
The span is defined as class "error" but you haven't defined that class.
I think it is better to bind blur and input events
the code:
Name.addEventListener('blur', function(){
if (!Name.value){
ErrName.innerHTML="Field Required";
this.classList.add('class');
ErrName.parentNode.style.color="red";
}
});
Name.addEventListener('input',function(){
if (Name.value.length && ErrName.innerHTML=="Field Required" ){
ErrName.innerHTML="";
this.classList.remove('class');
ErrName.parentNode.style.color="black";
}
});
a liddle fiddle

Validating a form with JavaScript not working

I have this code:
function validate(form) {
var errors = 0;
els = form.elements;
for (var i=0; i<form.elements.length; i++) {
if (!els[i].value && els[i].tagName != "select") {
console.log(els[i]);
els[i].style.border = "1px solid red";
errors = 1;
}
}
console.log("Finished for loop");
var skuld_fast = document.getElementsByName("skuld_fast")[0];
var skuld_other = document.getElementsByName("skuld_other")[0];
if ((skuld_fast.value && !skuld_other.value) || (!skuld_fast.value && skuld_other.value)) {
skuld_fast.style.border = "1px solid red";
skuld_other.style.border = "1px solid red";
errors = 1;
}
console.log("Finished if statement for skuld_fast and skuld_other");
if (errors == 0) {
form.submit();
}
else {
alert("Eitthvað fór úrskeiðis.");
}
}
The HTML:
<form>
<input name="input1">
<select name="skuld_other">
(...)
</select>
<select name="skuld_fast">
(...)
</select>
<input type="button" onClick="validate(this.form);">
</form>
input1 works fine. skuld_other and skuld_fast do not, regardless of whether anything is selected or not. The console.log statements are both printed.
The statement I'm trying to make with this code is this: For each element (input or select) in the for loop of form.elements, if nothing has been written into the field, and the tag name of the element is not select, or it is the case that only either of skuld_fast and skuld_other have been chosen, then I set errors = 1.
I should note that for select I am using Select Picker: http://silviomoreto.github.io/bootstrap-select/

Categories

Resources