Css - Select label far from input - html

I'm looking for a selector that let me style a label that's not near the respective input
Html
<article>
<header>
<label for="view-today-node-0">VIEW</label>
</header>
<input type="radio" name="view-today-node" id="view-today-node-0" />
</article>
I need to style the label when the radio is checked.
Something similar to
article input[type="radio"]:checked + label {}
but the label is not near the input

You can use the general sibling combinator (~) to style the label if it is not next to the input, but still a sibling:
input[type="radio"]:checked ~ label {
color:green;
}
Here is a fiddle: http://jsfiddle.net/EPHXU/

jQuery-Solution:
$("label[for='view-today-node']").css('background','#F00');

This might help. CSS alone won't be good for this, b4ttl3m4st3r was close I think. http://jsfiddle.net/a3v3x/
$("input[type='radio']").change(function(){
var color = this.checked ? "#f00" : "#000";
var id = $(this).attr('id');
$("label[for='"+id+"']").css('color',color);
});

Related

css input text name value color [duplicate]

Is it possible to use a CSS selector to target an input that has a specific value?
Example: How can I target the input below based on the value="United States"
<input type="text" value="United States" />
Dynamic Values (oh no! D;)
As npup explains in his answer, a simple css rule will only target the attribute value which means that this doesn't cover the actual value of the html node.
JAVASCRIPT TO THE RESCUE!
Ugly workaround: http://jsfiddle.net/QmvHL/
Original Answer
Yes it's very possible, using css attribute selectors you can reference input's by their value in this sort of fashion:
input[value="United States"] { color: #F90; }​
• jsFiddle example
from the reference
[att] Match when the element sets the "att" attribute, whatever the
value of the attribute.
[att=val] Match when the element's "att"
attribute value is exactly "val".
[att~=val] Represents an element
with the att attribute whose value is a white space-separated list of
words, one of which is exactly "val". If "val" contains white space,
it will never represent anything (since the words are separated by
spaces). If "val" is the empty string, it will never represent
anything either.
[att|=val] Represents an element with the att
attribute, its value either being exactly "val" or beginning with
"val" immediately followed by "-" (U+002D). This is primarily intended
to allow language subcode matches (e.g., the hreflang attribute on the
a element in HTML) as described in BCP 47 ([BCP47]) or its successor.
For lang (or xml:lang) language subcode matching, please see the :lang
pseudo-class.
css attribute selectors reference
It is possible, if you're using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs -- which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input {
color: black;
}
input:valid {
color: green;
}
<p>Which country has fifty states?</p>
<input type="text" pattern="^United States$">
Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
Sure, try:
input[value="United States"]{ color: red; }
jsFiddle example.
You can use Css3 attribute selector or attribute value selector.
/This will make all input whose value is defined to red/
input[value]{
color:red;
}
/This will make conditional selection depending on input value/
input[value="United States"]{
color:red;
}
There are other attribute selector like attribute contains value selector,
input[value="United S"]{
color: red;
}
This will still make any input with United state as red text.
Than we attribute value starts with selector
input[value^='united']{
color: red;
}
Any input text starts with 'united' will have font color red
And the last one is attribute value ends with selector
input[value$='States']{
color:red;
}
Any input value ends with 'States' will have font color red
Refreshing attribute on events is a better approach than scanning value every tenth of a second...
http://jsfiddle.net/yqdcsqzz/3/
inputElement.onchange = function()
{
this.setAttribute('value', this.value);
};
inputElement.onkeyup = function()
{
this.setAttribute('value', this.value);
};
In Chrome 72 (2019-02-09) I've discovered that the :in-range attribute is applied to empty date inputs, for some reason!
So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
Screenshot:
Here's a runnable sample:
window.addEventListener( 'DOMContentLoaded', onLoad );
function onLoad() {
document.getElementById( 'date4' ).value = "2019-02-09";
document.getElementById( 'date5' ).value = null;
}
label {
display: block;
margin: 1em;
}
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
<label>
<input type="date" id="date1" />
Without HTML value=""
</label>
<label>
<input type="date" id="date2" value="2019-02-09" />
With HTML value=""
</label>
<label>
<input type="date" id="date3" />
Without HTML value="" but modified by user
</label>
<label>
<input type="date" id="date4" />
Without HTML value="" but set by script
</label>
<label>
<input type="date" id="date5" value="2019-02-09" />
With HTML value="" but cleared by script
</label>
Following the currently top voted answer, I've found using a dataset / data attribute works well.
//Javascript
const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute
document.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", function() {
this.dataset.value = this.value;
console.log(this);
})
})
/*CSS*/
input[data-value="0.00"] {
color: red;
}
<!--HTML-->
<div>
<p>Input1 is programmatically set by JavaScript:</p>
<label for="input1">Input 1:</label>
<input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
<p>Try typing 0.00 inside input2:</p>
<label for="input2">Input 2:</label>
<input id="input2" value="undefined" data-value="undefined">
</div>

Add Background color after setting content in input field

Is there any way that i could add a background color after placing a content inside an input field? Just like what happens when an autocomplete works.
Thanks!
There are a few ways you could achieve this. You could make the input mandatory by adding the required attribute. Doing this means that as soon as the user enters anything into the field, it is now in the valid state and you can target it in your CSS using the :valid pseudo-class:
input:valid{
background:#ff9;
}
<input required>
Or, if you don't want to make the field mandatory and as others have suggested, you could set the new background-color when the field receives focus. To prevent it from reverting to its initial color when it loses focus, you will need to add a transition to the background, setting the transition-delay to some ridiculously high number when the input is in its normal state and resetting it to 0s when it is focused. Obviously, though, this change will occur whether or not the user actually enters anything in the field or not.
input{
transition-delay:9999s;
transition-property:background;
}
input:focus{
background:#ff9;
transition-delay:0s;
}
<input>
If neither of those options suit your needs then you will probably need to resort to using JavaScript to add or remove a class, depending on whether or not the value of the input is empty.
document.querySelector("input").addEventListener("input",function(){
this.value?this.classList.add("filled"):this.classList.remove("filled");
},0);
.filled{
background:#ff9;
}
<input>
Html
First name: <input type="text" name="firstname">
Css
input:focus {
background-color: yellow;
}
Demo in JsFiddle
Here is a solution with pure javascript
var input = document.getElementById("test");
input.addEventListener('input', function() {
if (input.value)
input.style.backgroundColor = '#90EE90';
else
input.style.backgroundColor = '#fff';
});
<input id="test" type="text" value="">
Add a Css class like
.myCSSClass
{
background-color:red;
}
Now using jquery on blur function you add this class
$("#myTextBox").on('blur',function(){
if($("#myTextBox").val()==""){
if($("#myTextBox").hasClass("myCSSClass")){
$("#myTextBox").removeClass("myCSSClass");
}
}
else
{
$("#myTextBox").addClass("myCSSClass")
}
});
Using Jquery,
$( "#target" ).blur(function() {
$( "#target" ).css('background-color','red');
});
DEMO

Select html through input:checked - pure css

Just wanted to know if anyone knew a way I can select and style the html tag directly after looking for :checked in css.
#btnControl:checked ??? html {
overflow: hidden;
}
Any feedback will be greatly appreciated! : )
Best, Jonathan
You can't select parent using CSS. But you can use class to do this work. Use javascript to add/remove class to element. When checkbox checked, add class to html and when checkbox unchecked, remove class of html.
var checkbox = document.getElementById("checkbox");
var html = document.getElementsByTagName("html")[0];
checkbox.addEventListener("change", function(){
if (checkbox.checked)
html.classList.add("checked")
else
html.classList.remove("checked")
});
html.checked {
background: orange;
}
<label for="checkbox">Click on checkbox</label>
<input id="checkbox" type="checkbox" />

How to create a "placeholder" for DIV that act like textfield?

Div don't have a placeholder attribute
<div id="editable" contentEditable="true"></div>
I want <Please your enter your Name> to show in DIV when the User backspace the whole text in the DIV, or no text on inside, How can I do it?
Here is a pure CSS only solution:-
<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-ph)
}
</style>
Here, we basically select all contentEditable <divs> that are empty & blurred. We then create a pseudo element before the CSS selection (the editable div) and fix our placeholder text (specified the data-ph attribute) as its content.
If you are targeting old school CSS2 browsers, change all occurrences of data-ph to title
Correction.......the :empty selector is not supported in IE version 8 and earlier.
What I find in other answers is that when using :not(:focus) pseudo class, I have to click again in order to get the blinking cursor and be able to type. Such issue doesn't happen if I click on an area other than the placeholder.
My workaround is simply removing :not(:focus). Even though in this way the placeholder will still be there after I click on the editable div, I'm able to type no matter where in the div I click, and the placeholder disappears immediately after I type something.
BTW, I inspected YouTube's comment div implementation, seems they are doing the same thing, e.g. #contenteditable-root.yt-formatted-string[aria-label].yt-formatted-string:empty:before
.editableDiv1,
.editableDiv2 {
border-bottom: 1px solid gray;
outline: none;
margin-top: 20px;
}
.editableDiv1[contentEditable="true"]:empty:not(:focus):before {
content: attr(placeholder)
}
.editableDiv2[contentEditable="true"]:empty:before {
content: attr(placeholder)
}
<div class="editableDiv1" contentEditable=true placeholder="If you click on this placeholder, you have to click again in order to get the blinking cursor and type..."></div>
<div class="editableDiv2" contentEditable=true placeholder="Click on placeholder is fine, it'll disappear after you type something..."></div>
You can try this one !
html:
<div contentEditable=true data-text="Enter name here"></div>
css:
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-text) }
check it out (demo)
in HTML
<div id="editable" contenteditable="true">
<p>Please your enter your Name</p>
</div>
in JavaScript
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("#editable").click(function() {
$("#editable").selectText();
});
jsFiddle

How to find the connection between a radio button and a label?

I have this label:
<label id="options_31409_3label" for="options_31409_3"><span>some text</span></label>
As you see, there is some text in the label inside a span. Now I also have a radio button, which is left of the label:
<input id="options_31409_3" class="radio" type="radio" value="72058" name="options[31409]" onclick="xyz()">...</input>
This is one radio and one label, but I have several radio buttons and labels on the same site. Now from those N labels and radio buttons I have to identify one pair and do some Prototype stuff with it. The pair has a different id each time the site is loaded, the only thing that stays is the text inside the span. Is there a way to get the label and the radiobutton if there is "some text" inside the span? I can use Prototype if that helps.
Thanks!
Because you know that label's id consists of input's id + 'label', you can use e.g. the following code to find a pair:
$$('input[type=radio]').each(function()
var input = this;
var label = $(this.id + 'label');
// do something for input and label
});
The labels for attribute, if used correctly, should have the same value as the inputs id attribute. So, you can easily find out which label belongs to which input like this:
$$('label').each(function () {
var label = this;
var input = document.getElementById(label.getAttribute('for'));
});
I would choose to improve jholser's snippet to work with all labels, not just those that have 'label' in their ID.
$$('input[type=radio]').each(function(input)
{
// Several labels may link to the same input
$$('label[for="' + input.identify() + '"]').each(function(label)
{
// do something for input and label
});
});