My function used to work, but now it won't. I'm trying to add an if statement for when the input is left blank, it returns to the default background color.
var path = /^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/g;
function col(obj) {
var val = obj.value;
if (path.test(val)) {
document.body.style.backgroundColor = '#' + val;
}
}
window.onload = function () {
document.getElementById('bgcol').onkeyup = function () {
col(this);
}
if (getElementById('bgcol'.value = null || ""){
document.body.style.backgroundColor = '#000000';
}
}
//end javascript, begin html below
<input id="bgcol" placeholder="enter hexadecimal color"></input>
You need document.getElementById and to clean up your syntax:
if ( document.getElementById('bgcol').value == null || document.getElementById('bgcol').value == "")
Working Fiddle
if (getElementById('bgcol').value == "") {
and
document.getElementById('bgcol').onkeyup = function () {
if (this.value == ""){
document.body.style.backgroundColor = '#000000';
}
else {
col(this);
}
}
and
<input id="bgcol" placeholder="enter hexadecimal color" />
Try this simplified version of your code:
window.onload = function() {
document.getElementById('bgcol').onkeyup = function() {
var col = this.value;
if( !col.match(/^#?(?:[0-9a-f]{3}){1,2}$/i)) col = "#000000";
if( col.charAt(0) != "#") col = "#"+col;
document.body.style.backgroundColor = col;
};
};
It uses a simpler regex and also allows the # to be accepted and optional.
Related
Hope someone can help. I'm new to JS and need some help.
I have the following code:
}
function onBall3Click() {
var ball3 = document.querySelector('.ball3');
alert('Ball3');
if (ball3.innerText == 'OFF') {
ball3.style.backgroundColor = 'yellow';
ball3.innerText = 'ON';
} else if (ball3.innerText == 'ON') {
ball3.style.backgroundColor = 'gray';
ball3.innerText = 'OFF';
}
}
function onBall4Click() {
var ball4 = document.querySelector('.ball4');
alert('Ball4');
var size = prompt("What should be the size of the ball?");
if (size > 1000) {
alert('Too Big!')
} else {
ball4.style.width = size;
ball4.style.height = size;
}
what I need to know is how to disable function onBall4click when the Ball3.innerText = 'OFF'
and how to enable the function once the Ball3.innerText = 'ON'
Appreciate all the support.
I am not an expert in Javascript but I think all you need to do is add a guard clause in the onBall4click function and check if Ball3 is ON before doing anything. The modified function would look something like this:
function onBall4Click() {
var ball3 = document.querySelector(".ball3");
if(ball3.innerText === "OFF") return;
var ball4 = document.querySelector('.ball4');
alert('Ball4');
var size = prompt("What should be the size of the ball?");
if (size > 1000) {
alert('Too Big!')
} else {
ball4.style.width = size;
ball4.style.height = size;
}
}
When you click on Ball 4, the function checks Ball3 and stops executing if it is off.
Here is my code
function CheckForm_1() {
var F1 = document.getElementById('srch');
var Lgth = document.getElementById('srch');
if (F1.value == "") {
document.getElementById("Empty_Err");
Empty_Err.style.display = 'inline';
Empty_Err.stylebackgroundColor = 'linen';
return false;
} else {
return true;
}
if (Lgth.value.length > 17 || Lgth.value.length < 4) {
document.getElementById("Length_Err");
Length_Err.style.display = 'inline';
backgroundColor = 'linen';
alert("Search length must be be between 4 and 17");
return false;
} else {
return true;
}
}
I can't get it to check the field length Any ideas on this?
The code will run a check for an empty field just fine.
Returning value will stop execution of a function.
As #Calvin Nunes commented
When you use return, you stop the function execution because you
returned a value, so the function is terminated...that's why you'll
never reach the second if, because in the first if you return or true
or false
function CheckForm_1() {
var F1 = document.getElementById('srch');
var errorMessage = document.getElementById("errorMessage");
if (F1.value == "") {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML= "Search field is empty";
} else if (F1.value.length > 17 || F1.value.length < 4) {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML = 'Search length must be be between 4 and 17';
} else {
errorMessage.style.display = 'none';
}
}
<input id='srch' type="text" />
<div id="errorMessage" style="display:none">Search field is empty</div><br>
<button type="button" onclick="CheckForm_1()">Submit</button>
I have one textbox.It should be allow only decimal numbers and after dot only allow two digit(example 34545.43). how we can do it using jquery i have searched in google and stackoverflow but not satisfied answer because some script is not working in chrome and firefox. I tried but it is not working properly.So need help how to do it.http://jsfiddle.net/S9G8C/1685/
Js:
$('.allow_decimal').keyup(function (evt) {
var self = $(this);
self.val(self.val().replace(/[^0-9\.]/g, ''));
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
evt.preventDefault();
}
});
This jQuery function will round the value on blur event of textbox
$.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(2);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() { //This function will work on onblur event
$('#txt').blur(function() {
$(this).val($(this).getNum());
});
});
Number: <input type="text" id="txt" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can directly remove the 3rd digit when the user enters that.
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
<input id="txtId" type="text"></input>
I have a problem with my code and I would appreciate if you help me. The problem is - when you fill in all inputs in the form correctly, the script removes attribute "disabled" from the submit button but for example if you clear all fields after filling in the forms, submit button will be able to submit the form, but it have to back attribute "disable". how can I fix it?
//validation name
document.callbackform.name.onkeyup = function() {
var name = document.callbackform.name.value;
if (name === "") {
document.callbackform.name.removeAttribute("class", "ready");
document.getElementById("callError").style.display = "block";
document.getElementById("calllErrorTwo").style.display = "none";
} else {
document.getElementById("callError").style.display = "none";
var pattern = new RegExp("^[а-я]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.getElementById("calllErrorTwo").style.display = "block";
document.callbackform.name.removeAttribute("class", "ready");
} else {
document.getElementById("calllErrorTwo").style.display = "none";
document.callbackform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.callbackform.phone.onkeyup = function() {
var name = document.callbackform.phone.value;
if (name === "") {
document.callbackform.phone.removeAttribute("class", "ready");
document.getElementById("calltelError").style.display = "block";
document.getElementById("calltelErrorTwo").style.display = "none";
} else {
document.getElementById("calltelError").style.display = "none";
var pattern = new RegExp("[- +()0-9]+");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.getElementById("calltelErrorTwo").style.display = "block";
} else {
document.getElementById("calltelErrorTwo").style.display = "none";
document.callbackform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.callbackform.onkeyup = function() {
var a = document.callbackform.name.getAttribute("class");
var c = document.callbackform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("subCallback").removeAttribute("disabled");
document.getElementById("subCallback").style.cursor = "pointer";
} else {
document.getElementById("subCallback").setAttribute("disabled");
document.getElementById("subCallback").style.cursor = "not-allowed";
}
};
Simple fix. .setAttribute("disabled"); doesn't work as disabled is a property, not an attribute, as it does not have a value. You simply need to use .disabled = true; as shown:
document.getElementById("subCallback").disabled = true;
It will also be good to use the following to remove the disabled property:
document.getElementById("subCallback").disabled = false;
.
Remember, setAttribute() always requires two arguments, the second argument being the attribute value.
hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}