Coloring text with css using jQuery - javascript

I have a little problem adding a class to a span element and so coloring it in order to perform simple validation.
Here is my js:
function validateKey(){
var length = $('#appkey').val().length;
if(length != 8){
$('#appkey').addClass('error');
$('#appKeyInfo').addClass('error');
return false;
}else{
$('#appkey').removeClass('error');
$('#appKeyInfo').removeClass('error');
return true;
}
}
And html:
<label>KEY</label></br>
<input type="text" id="appkey" value=""/></br>
<span id="appKeyInfo">Dein App-Key aus 8 Ziffern</span>
And the jsfiddle: example
Any ideas?
UPDATE: coloring of appKeyInfo fails, coloring appkey works. When I remove color:red and type font-weight:bold instead the text is bold on error. when I remove color definition of appKeyInfo the text can be colored red on error, strange thing, but I need a font color for the appKeyInfo

The declaration for span#appKeyInfo takes precedence since it is an id you are styling.
Try using color:red !important to force the override
Edit
Just a note, you can use multiple selectors in your jQuery. Like this:
$('#appkey', '#appKeyInfo').removeClass('error');

your comparison operator is wrong, use less than operator :
function validateKey(){
var length = $('#appkey').val().length;
if(length < 8){
$('#appkey').addClass('error');
$('#appKeyInfo').addClass('error');
return false;
}else{
$('#appkey').removeClass('error');
$('#appKeyInfo').removeClass('error');
return true;
}
}

Related

How to set text decoration for "this".sibling

I'd like to make a text decoration of `line-through' when a checkbox is checked and remove the decoration when the checkbox is unchecked.
This is my js:
if ($(this).is(':checked')) {
$(this).siblings('label').style.textDecoration = "line-through";
} else {
$(this).siblings('label').style.textDecoration = "none";
}
With the current code I get the error of
Uncaught TypeError: Cannot set property 'textDecoration' of undefined
and I'm assuming it is because it doesn't like my this.siblings string.
try this one.
$(this).siblings('label').css('text-decoration', 'line-through');
$(this).siblings('label').css('text-decoration', 'none');
If your label is after the checkbox input, you can use plain CSS and the Next Sibling operator +
input[type=checkbox]:checked + label{
text-decoration: line-through;
}
<input type="checkbox" id="a1" name="a1"><label for="a1">UNCHECKED</label>
if it's not an immediate sibling than you can use the Sibling Operator ~ instead of +.
.style is plain JS and refers to only one element while you're handling an array of jQuery selectors Elements.
So yes, user jQuery's .css() method to apply the changes to all your elements (jQuery will loop all of them internally like you would in JS using for loop or forEach)
If you want you can also do it using a conditional operator ?: (without the if else) simply like:
$(':checkbox').on("change", function(){
$(this).siblings('label').css({"text-decoration": this.checked ? "line-through" : "none"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" id="a1" name="a1"> <label for="a1">UNCHECKED</label>
</p>
If you want you can mix jQuery and JS here's an example:
$("#element")[0]/*or use .get(0)*/.style.textDecoration = "none";
but as I've said before it cannot be applied to multiple elements if not used inside a loop, passing that current index as the get value:
$(".elements").each(function(i){
$(this)[i].style.textDecoration = this.checked ? "line-through" : "none" ;
});
which is a mix of jQuery and JS's:
for(var i=0; i<myJSelements.length; i++){
myJSelements[i]/* etc... */
}
Does .sibling('label') return an element or Text?
If it returns Text, then that is your problem.
Apply .style.textDecoration to the element.
The function identifies the text node in the element and decorates it.

How do I iterate through div's child elements and hide them?

I have a div that have a few elements that I want to hide, on users request. Those elements have a particular background color. The call of the function is working (it is associated to a checkbox) but it just doesnt do what i want. Actually, it does nothing. This is what I've got:
function toogleDisplay()
{
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.style.backgroundColor=="#A2B5CD")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
What am I doing wrong?
An element's background colour is converted to rgb() (or rgba()) format internally.
But that aside, assuming $ is jQuery (you haven't tagged your question so I don't know!) then a is a jQuery object, which does not have a style property. It looks like you just wanted var a = kiddos[i];.
It is more reliable to use a specific class name instead.
You re wrapping your kiddos[i] in a jquery-object $(kiddos[i]) and then try to access the normal properties of a html-dom-objekt.
You have 2 possibilities:
remove the $()
use jquery-access to the properties
a.css('display', none); // or just a.hide();
Additionally you cant check for '#123456' since the color is transformed. Check (#Niet the Dark Absol)s answer for this
I would suggest adding a class to the elements you want to check. Then instead of trying to use background, you can do
$(kiddos[i]).hasClass('myclass')
or for a very efficient way, you can do it in one line of code.
function toogleDisplay()
{
$('.myclass').toggle(); //this will toggle hide/show
}
The divs would look like this
<div class='myclass'>Content</div>
EDIT - to do it without modifying existing html. I also think the rbg color should be rgb(162, 181, 205) if im not mistaken.
You can try something like this. Its based off the following link
Selecting elements with a certain background color
function toogleDisplay()
{
$('div#external-events').filter(function() {
var match = 'rgb(162, 181, 205)'; // should be your color
return ( $(this).css('background-color') == match );
}).toggle()
}
Your jquery selection of a is causing issues. Unwrap the $() from that and you should be fine.
Also you could end up selecting text nodes that wont have a style property. You should check that the style property exists on the node before trying to access background, display, etc.
Use a class instead of a background and check for that instead.
i think you need to see if the 'nodeType' is an element 'a.nodeType == 1' see Node.nodeType then it will work over multiple lines
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.nodeType == 1){ // Check the node type
if (a.style.backgroundColor=="red")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
I decided to go for another aproach, using the idea of Kalel Wade. All the elements that may be (or not) hidden, already had a class name, which were the same for all elements, fortunately.
here comes the code
function toogleDisplay()
{
var kiddos = document.getElementsByClassName("external-event ui-draggable");
for (var i = 0, len = kiddos.length; i < len; i++) {
var a=kiddos[i];
if (a.style.backgroundColor==="rgb(162, 181, 205)")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}

Need to get is any child inside an element is having a background

I need to find out is their any span having a style of background so I can get value from its attribute I have $(this). Structure is:
<div id="operative_time_limit" class="timedivd">
<span title="1 hours" data-y="1" data-x="0"></span>
<span title="2 hours" data-y="2" data-x="0"></span>
<span title="3 hours" data-y="3" data-x="0"></span>
<span title="4 hours" data-y="4" data-x="0"></span>
</div>
Using alert(jQuery(this).children().css('background').length); but always getting 0 as result
try this,
alert($('#operative_time_limit').find('span').length);
For span which has background-color property then try it like,
var c=0;
$('#operative_time_limit').find('span').each(function(){
if($(this).css('backgroundColor')) // or 'background-color'
c++;
});
alert(c);
I am not sure what exactly $(this) is in your context.
However the following:
var count = 0;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
count++;
}
});
alert(count);
Will do it. Further extrapolating from your question to presume that you want to extract some attribute (lets call it someAttr), from the span with a background of css, and there is only one such span. Assuming those are correct assumptions, the following will give you what you want:
var attributeValue;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
attributeValue = $(this).attr('someAttr');
}
});
You now have your desired value in attributeValue
The following line will give you the length of Children of $(this)
alert(jQuery(this).children().css('background').length);
You could use the following code to find all the span's that have background color other than white (assuming white is default color)
var length = $('#operative_time_limit').children().filter(function () {
return $(this).css('background-color') != 'rgba(0, 0, 0, 0)' && $(this).css('background-color') != 'transparent';
}).length;
here, variable length can be used to determine how many spans have background property
See working fiddle
use following
alert(jQuery(this).children().hasClass('background')).
hasClss determines whether any of the matched elements are assigned the given class.
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are

Change the border color if input value is null

I wanted to do is change the color of ALL the input text borders at the same time if it/they have null or no value upon clicking the button, I have a function to do this.
First I put the input text that I want to check the values into an array, then call the function where in it loops through the array and check for the null values. On button click, if all of my input text are null it will only change the color of the first index in the array.
Here is my function:
function isValid(array){
for(var x=0;x<array.length;x++){
if (array[x].value.trim() == ""){
$(array[x]).css("border-color","#FF0000");
return false;
}
}
}
This is how I call my function:
var array = [document.getElementById('txtLastName'),
document.getElementById('txtFirstName')
];
if (!isValid1(array)) {
return false;
}
How to change the border color of all the input in the array with null values?
Thanks!
Here's my two cent, may need tuning:
function isValid(selector){
return ($(selector).filter(function() {
return (this.value.trim() === "");
}).css("border-color","#FF0000").length === 0);
}
To use it:
isValid("#txtLastName, #txtFirstName");
I build the CSS selector in caller and pass it to isValid(), you could have passed the array ["txtFirstName", "txtFirstName"] and build the selector in isValid().
There are many ways to do this, a more modular approach is to use a nullValidate class as selector, so you can have as many validated field as you like.
EDIT: return if invalid elements are found
Why a mix of jQuery and vanilla JS .. Can just use filter method.
$('#txtLastName, #txtFirstName').filter(function() {
return $.trim(this.value) === '';
}).css("border-color","#FF0000");
Also there is nothing wrong with the way you have written the code.
You must have not been using the correct id most probably.
Your Code
JQuery Code
Just my 2 cents worth
<form name="form">
<input type="text" name="firstname" />
<input type="button" name="submit_btn" value="send" />
</form>
$(document).ready(function(){
$('input[type="text"]').keyup(function(){
var length = $('input[type="text"]').val().length;
if(length===0){
$(this).css({"border":"1px solid red"});
}
else {
$(this).css({"border": ""});
}
});
$('input[type="button"]').click(function(){
var length = $('input[type="text"]').val().length;
if(length===0){
$('input[type="text"]').css({"border":"1px solid red"});
} else {
$('input[type="text"]').css({"border":""});
}
});
});

jQuery, selecting just number from id like "article-23"

All right, I have a div tag which got a class="blog-post" and id like id="article-23" (where "23" could be any number, as it is id of blog post in a database). I need to somehow get just a number from that id and than apply some rules to that div tag. So say:
if number from id % 2 == 0 {
set text colour black to associated div tag with class of blog-post
} else {
set text colour white to associated div tag with class of blog-post
}
Thats just a "pseudo" code to show logic that I wan't to apply dependent if number from id is even or odd, but the question remains same, how do I just get number from id like "article-23" ?
As simple as
var number = "article-23".match(/\d+/)[0];
But you have to be sure that any digit exists in the string, otherwise you'd get a error.
You can actually apply rules via function, which makes this the cleanest solution (in my opinion):
$(".blog-post").css('color', function () {
return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/
Try this:
$('.blog-post[id^="article-"]').each(function () {
if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
$('#' + this.id).css('color', 'black');
} else {
$('#' + this.id).css('color', 'white');
}
});
jsFiddle Demo
As an alternative, HTML5 supports these things called "data attributes", which are specifically meant for attaching data to your DOM without abusing things like the "class" or "id" attributes. jQuery provides a handy .data method for reading these attributes in a more obvious way.
You can add your own numeric ID attribute using something like "data-id":
<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
console.log($(this).data("id")); // Look up the data-id attribute
});
If I'm understanding correctly, you want the number after the hyphen of the id tag of your .blog-post class.
var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-"); // split it on hyphens
return article = article[article.length-1]; // return the last element

Categories

Resources