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>
Related
I've created an input control with validation:
required
minlength = 4
maxlength = 8
The input's initial value set to 'ab'.
Since the 'ab' doesn't satisfy the validation, the :invalid selector should work.
But at the first load (unedited by user), the :invalid doesn't work.
Is there any way to force validation in all time?
<input type='text' id='test' value='ab' required minlength=4 maxlength=8 />
#test:valid {
background: lightGreen;
}
#test:invalid {
background: pink;
}
Looks like it's always saying it's valid.
Have you tried putting ""'s around the 4 and 8 values?
Like so:
minlength="4"
maxlength="8"
Can you post more of your code?
Is it possible to style the value in the attribute ngModel of an input tag?
Example:
<input class="input" type="text" [(ngModel)] = "myService.text">
Let's say the value of text is '28 packages', can I put 28 in bold?
So if i understand correctly you want to have it bold whenever the value is 28 ?
yes its possible you can use a ng-class with a ternary expression like this
.bold{
font-weight:600;
}
<input type="text" ng-class="myService.text == '28 ? 'bold' : '''" class="input" ng-model="myService.text" />
This is not angular-related rather a CSS related question.
You cannot style only a part of an input in HTML/CSS so you won't be able to do it in angular.
Instead, you can use an input that is hidden behind a div. The idea is that when the user clicks the div, you actually focus the input. When the user types text, you capture the content of the input and fill the div with it, eventually adding <span class"highlight"> around the number of packages.
I prepared you a stackblitz in pure CSS/JS. You can adapt it in angular if you want.
Relevant pieces of code :
HTML :
<span id="hiddenSpan">This is the hidden div. Click it and start typing</span>
<div>
<label for="in">The real input</label>
<input id="in" type="text">
</div>
JS :
const input = document.getElementById('in')
const hiddenSpan = document.getElementById('hiddenSpan')
function onInputChanged() {
let text = input.value
const regex = new RegExp('(\\d+) packages')
let result = regex.exec(text)
if(result) {
hiddenSpan.innerHTML = '<span class="highlight">'+result[1]+'</span> packages'
} else {
hiddenSpan.innerHTML = text
}
}
// Capture keystrokes.
input.addEventListener('keyup', onInputChanged)
// Focus the input when the user clicks the pink div.
hiddenSpan.addEventListener('click', function() {
input.focus()
})
CSS :
#hiddenSpan {
background-color: pink;
}
.highlight {
font-weight: bold;
background-color: greenyellow;
}
Note : the downside is that the blinking caret is not visible anymore. You can take a look at this resource if you want to simulate one.
It is not possible to style certain parts of a text <input> field in bold. However, you can use a contenteditable div instead of a text <input> field. Inside the contenteditable div you can have other HTML tags like <strong> to style certain parts of the text however you like.
I created an Angular directive called contenteditableModel (check out the StackBlitz demo here) and you can use it to perform 2-way binding on a contenteditable element like this:
<div class="input" contenteditable [(contenteditableModel)]="myService.text"></div>
The directive uses regular expressions to automatically check for numbers in the inputted text, and surrounds them in a <strong> tag to make them bold. For example, if you input "28 packages", the innerHTML of the div will be formatted like this (to make "28" bolded):
<strong>28</strong> packages
This is the code used in the directive to perform the formatting:
var inputElement = this.elementRef.nativeElement;
inputElement.innerHTML = inputElement.textContent.replace(/(\d+)/g, "<strong>$1</strong>");
this.change.emit(inputElement.textContent);
You can change the <strong> tag to something else (e.g. <span style="text-decoration: underline"> if you want the text to be underlined instead of bolded).
When performing the formatting, there is an issue where the user's text cursor position will be unexpectedly reset back to the beginning of the contenteditable div. To fix this, I used 2 functions (getOriginalCaretPosition and restoreCaretPosition) to store the user's original cursor position and then restore the position back after the text formatting is performed. These 2 functions are kind of complex and they're not entirely relevant to the OP's question so I will not go into much detail about them here. You can PM me if you want to learn more about them.
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
The input type="color" has a default color which is black: #000000.
Even if I give it an empty value...
<input type="color" value="" />
...the default color is always black.
I want the user to have the option of picking a color, but if he doesn't it means no color was picked, not even white #FFFFFF.
Is there a way to force an input type="color" not to have black color as default?
I can use some kind of a "listener" to check if the user changed the color for the first time, if not, ignore the value, but I would like to avoid Javascript.
While using hexcode for value attribute in <input type="color">, one thing I noticed is that it has to be six digits, if for white you use #fff, it does not work. It has to be #ffffff.
The same thing happens when setting it through javascript.
document.querySelector('input[type="color"]').value = '#fff' does not work. The color remains black.
You have to use document.querySelector('input[type="color"]').value = '#ffffff' for it to work.
Something to be careful about.
Use value:
<input type="color" value="#ff00ff" />
If you want to know if input remain unchanged, you can do something like this (with jQuery):
$(function(){
$('input').change(function(){
$(this).addClass('changed');
})
})
http://jsfiddle.net/j3hZB/
Edit: Now since, I have understood your question correctly, I have updated my answer.
Although the W3C Spec defines that the value attribute has a string representing the color, it doesn't define the default color. So I think that the implementation of default color is left at the discretion of the browser.
However, the WhatWG Spec anwers your question with this note,
Note: When the input type element is in the color state, there is always a color picked, and there is no way to set the value to the empty string.
Moreover, based on your expectation, the CSS language never defined a NULL attribute for any element, which makes it impossible for the input type='color' to have NULL as the default value.
Workaround:
The workaround is present in the Shadow DOM API.
Using Chrome Developer Tools, I found that we can give a transparent color to the pseudo element ::-webkit-color-swatch background property -
input[type=color]::-webkit-color-swatch
{
background-color: transparent !important;
}
For the above CSS, your HTML should like this - <input type="color">. Now you don't need to have any kind of listener to tell if the user has changed the default color or not. You can simply treat the transparent color as the NULL color based on which you can make a decision whether the value was changed or not!
I am sure that you will find similar kind of information from the Shadow DOM for Firefox to set transparent value for background. IE still remains a pain for us.
Here is my solution, switching input type from text to color:
$(document).on('click', '.dc-color-input-switcher', function() {
var dcInputColor = $(this).parent().parent().prev();
if (dcInputColor.attr('type') == 'text') {
dcInputColor.attr('type', 'color');
} else {
dcInputColor.attr('type', 'text');
}
});
$(document).on('click', '.dc-color-input-clearer', function() {
var dcInputColor2 = $(this).parent().parent().next();
if (dcInputColor2.attr('type') == 'color') {
dcInputColor2.attr('type', 'text');
}
dcInputColor2.val('');
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group">
<div class="input-group-btn">
<div class="btn-group">
<span title="Empty" class="btn btn-danger dc-color-input-clearer" data-original-title="Empty Field"><i class="fa fa-times"></i></span>
</div>
</div>
<input name="product_tabs[1][0][bg_color]" value="" placeholder="Background Color" class="form-control pre-input-color" type="text">
<div class="input-group-btn">
<div class="btn-group">
<span title="Toggle color picker" class="btn btn-primary dc-color-input-switcher" data-original-title="Switch color picker"><i class="fa fa-paint-brush"></i></span>
</div>
</div>
</div>
The answer can be twofold.
For display purposes, yes, you can set a default color just by setting the value of the input to the color you want. You can see varieties of this in the answers on this page.
Technically, no. It is not possible to send an empty value as color through POST. The POSTed value will always default to #000000 or the color which you have set default (as mentioned in 1.).
After some thought on this, perhaps a practical solution for this might be to choose #010101 as a reference to null or false or whatever. This leaves room for some jQuery (or javascript) to make it less likely that this value can be set.
<input type="color" name="myColor" required="" />
For instance, on one hand the color inputs that are set to required can be given the value #010101 at event load. And to be sure, prevent users selecting the color #010101.
(function($){
"use strict";
// Set all required color input values to #010101.
$(window).on("load", function() {
$("[type='color'][required]").val() == "#010101";
});
$("[type='color'][required]").on("change", function() {
// Prevent users selecting the color #010101.
if($(this).val() == "#010101") {
$(this).val() == "#000000";
}
});
})(jQuery)
At the time of server-side validation, #010101 is considered as empty (or false, etc.).
<?php
$color = htmlspecialchars($_POST['myColor']);
if($color == "#010101") {
// Do variable empty routine
} else {
// Do variable has value routine
}
?>
*Now you can be pretty sure to know if the user has set the value, as long as the UA has javascript capabilities.
The drawback is the setting of the color on load. Reload with a pre-set value is not possible this way. Perhaps this can be improved with the use of sessionStorage.*
But the real point is: Why am I doing this? I don't think it should be neccessary, the default value of #000000 is the single deviation from the normal workings of an input type. Except for the range input type, which also has an optional default value, this color input type is very different.
Don't know if this issue is only available on chrome, but I just found the quick fix for chrome. We need to set the input value to #FFFFFF first and after that set it to default value, the default color will appear instead of black
var element = document.querySelector('input[type="color"]');
element.value = '#FFFFFF'; //remember the hex value must has 7 characters
element.value = element.defaultValue;
Hope it help someone :)
This works fine for setting a different default color from black:
<input
type="color"
value="#123456"
onChange={(e) => handleBGColor(e)}
></input>
However when I was using shorthand 3-hex values like "#000" or "#FFF" instead of 6 like above it did not work.
I have implemented this kind of solution for myself. It displays nice "transparent" button. When clicked it triggers the normal hidden input-color. When color is picked up, the transparent button will hide and the input-color will show up.
Cheers.
function clickInputColor( button )
{
$( button ).next().click();
}
function inputColorClicked( input )
{
$( input ).show();
$( input ).prev().hide();
}
.inputEmptyColorButton {
background:url("http://vickcreator.com/panel/images/transparent.png") center repeat;
width: 50px;
height: 1.5em;
vertical-align: bottom;
border: 1px solid #666;
border-radius: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="clickInputColor( this );" class="inputEmptyColorButton"></button>
<input onchange="inputColorClicked( this );" style="display: none;" type="color" value="" />
Is there a way I can also set some label text for each steps in the HTML5 type=range control. Basically I have a range control <input type="range" step=1 min=0 max=4> and for each steps I want some label to be shown in the control. Is there a way to do this?
I've put together for you.
// define a lookup for what text should be displayed for each value in your range
var rangeValues =
{
"1": "You've selected option 1!",
"2": "...and now option 2!",
"3": "...stackoverflow rocks for 3!",
"4": "...and a custom label 4!"
};
$(function () {
// on page load, set the text of the label based the value of the range
$('#rangeText').text(rangeValues[$('#rangeInput').val()]);
// setup an event handler to set the text when the range value is dragged (see event for input) or changed (see event for change)
$('#rangeInput').on('input change', function () {
$('#rangeText').text(rangeValues[$(this).val()]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" id="rangeInput" name="rangeInput" step="1" min="1" max="4">
<label id="rangeText" />
I guess the easiest solution (plain Javascript) is:
<fieldset>
<label for="rangeVal">resolution (dpi):</label>
<input type ="range" max="1000" min="20"
oninput="document.getElementById('rangeValLabel').innerHTML = this.value;"
step="1" name="rangeVal" id="rangeVal" value="200">
</input>
<em id="rangeValLabel" style="font-style: normal;"></em>
</fieldset>
This code does not need jQuery nor CSS and should work on any browser that supports the range input type.
Here's an alternative solution, no jQuery required. Uses the HTML5 oninput event handler, and valueAsNumber property of the input element.
Works on my machine certification: Chrome v54
<form name="myform" oninput="range1value.value = range1.valueAsNumber">
<input name="range1" type="range" step="1" min="0" max="4" value="1">
<output name="range1value" for="range1" >1</output>
</form>
OP,
I put together a demo that uses a range input with corresponding <p> tags that act as both labels for the current state of the slider, as well as triggers to change the slider's value.
Plunk
http://plnkr.co/edit/ArOkBVvUVUvtng1oktZG?p=preview.
HTML Markup
<div class="rangeWrapper">
<input id="slide" type="range" min="1" max="4" step="1" value="1" />
<p class="rangeLabel selected">Label A</p>
<p class="rangeLabel">Label B</p>
<p class="rangeLabel">Label C</p>
<p class="rangeLabel">Label D</p>
</div>
Javascript
$(document).ready(function(){
$("input[type='range']").change(function() {
slider = $(this);
value = (slider.val() -1);
$('p.rangeLabel').removeClass('selected');
$('p.rangeLabel:eq(' + value + ')').addClass('selected');
});
$('p.rangeLabel').bind('click', function(){
label = $(this);
value = label.index();
$("input[type='range']").attr('value', value)
.trigger('change');
});
});
CSS
input[type="range"] {
width: 100%;
}
p.rangeLabel {
font-family: "Arial", sans-serif;
padding: 5px;
margin: 5px 0;
background: rgb(136,136,136);
font-size: 15px;
line-height 20px;
}
p.rangeLabel:hover {
background-color: rgb(3, 82, 3);
color: #fff;
cursor: pointer;
}
p.rangeLabel.selected {
background-color: rgb(8, 173, 8);
color: rgb(255,255,255);
}
Also worth nothing, if you're interested in showing the current value as a label/flag to the user, (instead of many) there's a great article by Chris Coyier on value bubbles for range sliders.
There is no native way of doing it. And as input[type=range] is very poorly supported, I will recommend using jQuery UI slider and the way of attaching labels found here in answer.
You can use jSlider. Its a jQuery slider plugin for range inputs.
https://github.com/egorkhmelev/jslider
Just check out the demos and documentation. Hope this helps.
FWIW the standard (HTML 5.1, HTML Living Standard), specifies a label attribute for options when using a datalist. Sample code here.
This isn't implemented by any browser yet.