How can I capitalize the first letter of an input? - css

I'm currently trying to capitalize the very first letter from an input.
Here's what I tryed :
fieldset input
{
text-transform:capitalize;
}
But it doesn't work the way I want, as every word is capitalized.
I also tryed this :
fieldset input:first-letter
{
text-transform:uppercase;
}
But it seems <input /> doesn't work at all with first-letter...
Anyway, do you have any idea of how to achieve this without javascript (or as little as possible) ?

JS: str.charAt(0).toUpperCase();

Impossible. It is possible with Javascript, or by putting only the first word within a span.

$('#INPUT_ID').keyup(function(){
if($(this).val().length>0 && $(this).val().length<5){
$(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
}
});
Can't use length==1, as it doesn't work if user types fast.

Inputs can't have first letter capitalized only with CSS, not even :first-letter pseudoselector. We have to use Javascript.
We will use class name capitalized on every input for which we want to have the first letter capitalized.
HTML:
<input type="text" class="capitalized" />
The idea is to listen for change on input (focusout), take the value, capitalize first letter, join it with the rest of the value and set it as new value.
You can use keyup, but that becomes overkill after the first keyup - nothing will change there.
JS (jQuery flavor):
$('.capitalized').on('change', function () {
let entered = $(this).val();
let firstLetter = entered.charAt(0).toUpperCase();
let rest = entered.substring(1);
$(this).val(firstLetter + rest);
});

You must use
<fieldset>
<legend>DATA...</legend>
<input type="text" class="inputName" placeholder="Введите имя">
without <input />
then in CSS:
fieldset input {
text-transform: capitalize;
}

Related

CSS only input range to change background 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>

Input type="number" with pattern="[0-9]*" allows letters in firefox

So, all question is in the topic's title. Input type="number" with pattern="[0-9]*" works fine in Chrome, but allows letters in FF. Is there any way to fix it without using jQuery or JS?
.small-input {
-moz-appearance: textfield;
}
.small-input::-webkit-inner-spin-button {
display: none;
}
.small-input::-webkit-outer-spin-button,
.small-input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
}
<input class="small-input " pattern="[0-9]*" value="" type="number">
You could use Regex to completely prevent the user from entering in any letters into the input field.
So on your input element I would add the following event listener: onkeypress="preventNonNumericalInput(event)"
<input class="small-input " pattern="[0-9]*" value="" type="number" onkeypress="preventNonNumericalInput(event)">
And then in your JavaScript file you'd create the following function:
function preventNonNumericalInput(e) {
e = e || window.event;
var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
var charStr = String.fromCharCode(charCode);
if (!charStr.match(/^[0-9]+$/))
e.preventDefault();
}
I've tested this and it should prevent any non numerical input and any special characters eg ##./? etc...
Seems that Firefox doesn't restrict you from entering alphabetic characters into a number input, however it still will validate the input upon submitting your form as seen below. Note that both e and E are valid in numeric inputs.
Also, according to MDN,
<input type="number"> elements do not support use of the pattern
attribute for making entered values conform to a specific regex
pattern. The rationale for this is that number inputs can't contain
anything except numbers, and you can constrain the minimum and maximum
number of valid digits using the min and max attributes
So no need to use it.
Selecting a numeric input really does two things. First on mobile devices is should bring up a numeric keypad instead of a normal keyboard to enter input, second it should only allow numbers as valid input. So if you want to prevent a user from entering text into one, you'll need JavaScript.
You'll see by the example below that when you try and submit the form, if the input isn't numeric it will prompt you to correct it, and the pattern attribute is unnecesary:
.small-input {
-moz-appearance: textfield;
}
.small-input::-webkit-inner-spin-button {
display: none;
}
.small-input::-webkit-outer-spin-button,
.small-input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<form>
<input class="small-input" value="" type="number">
<button>Button</button>
</form>
elements do not support use of the pattern attribute for making entered values conform to a specific regex
pattern. The rationale for this is that number inputs can't contain
anything except numbers, and you can constrain the minimum and maximum
number of valid digits using the min and max attributes, as explained
above.
Link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
You should use Javascript instead, following this link.
For anyone interested in syntax which is using non-deprecated properties (which, keyCode):
const handleAllowNumbers = (e) => {
if (e.target.type === "number" && !e.key.match(/^[0-9]+$/)) {
e.preventDefault();
}
};
It will work with country code "[0-9]+$" (regex format).
Note: Blank space are allowed with above regex code.
Without blank space-
It will work with country code "^[-+()][0-9][-+()0-9]$".
Note: Blank space are not allowed with above regex code.
Working for chrome, firefox & safari (latest browser version)
<input
class="form-control"
min="1"
type="text"
maxlength="1000000"
#keypress="onlyNumber"
>
and method
function onlyNumber ($event) {
let keyCode = ($event.keyCode ? $event.keyCode : $event.which);
if ((keyCode < 48 || keyCode > 57) && keyCode !== 190) { // 46 is dot
$event.preventDefault();
}
},

Is there any way to show bullets instead of numbers in input field

I require to show the bullets instead of numbers in my input field. for that is there any easiest way? I like to use some bullet based fonts so number will be hidden.
if so, any one share me a free fonts which gives only bullets for numbers?
<input type="tel" value="●">
I tried like above. but still i like to go for bullet fonts.
If it's the ability to view and hide it's value, you could use a bit of JS to set its type attribute to tel or password?
<input type="password" id="field">
<script>const toggleVisibility = () => {
let element = document.querySelector("#field");
element.setAttribute("type", (element.getAttribute("type") == "password") ? "tel" : "password");
}
</script>
Hope that helps, if that's not what you're looking for, then you might find this CSS property useful: -webkit-text-security: disc;
Try this:
input {
-webkit-text-security: disc;
}

CSS3 - Color item based on certain condition

I have a table with a column "amount". If the item in the cell is positive I want it to be colored in green, if not in red.
This can be done very easily using jQuery but I wondered if there's any trick using new CSS3 features that could help me achieve this without using javascript at all.
Is this possible?
Perhaps you can arrange for the server to generate HTML with data-* attributes containing the value. Then:
<span data-value="-123">-123</span>
[data-value^="-"] {
color: red;
}
In words, "if the value of the data-value attribute starts with a minus sign, color the text red."
Another idea is to use the :invalid pseudo-class. This will only work for an input element, unfortunately. However, you can disable it to prevent input and style it so it looks like regular text. You will also have to arrange to have the value placed in the value attribute of the input element:
<!-- specify a pattern which permits only positive numbers -->
<input type="text" pattern="\\d*" value="-123" disabled>
input:invalid {
color: red;
}
Neither of these approaches is ideal; you'll probably end up using JS.
When you return the data for the table, you will need to add a class to the TD for your amount column for any value is less than 0. You could use "negative" and give this a style of colour:RED; You can set the default style for the amount column TD as green for all positive values, and when the browser encounters the "negative" style it will set negative values to be red.
Use something like this:
<style>
.positive
{
background:green;
}
.negative
{
background:red;
}
</style>
<script>
function colorBackground(){
if (document.getElementById('yourid').value < 0){
document.getElementById('yourid').style.bgColor = "red";
}else {
document.getElementById('yourid').style.bgColor = "green";
}
}
</script>
Apparently this can't be done using CSS3 only.
Here is the jQuery code I used in the end:
$( document ).ready(function() {
$(".amount").each(function() {
$(this).addClass($(this).text() >= 0 ? "positive" : "negative");
});
});
If anyone has any shorter version of it, I'd be happy to have it :)
Thanks

CSS text-transform capitalize on all caps

Here is my HTML:
small caps &
ALL CAPS
Here is my CSS:
.link {text-transform: capitalize;}
The output is:
Small Caps & ALL CAPS
and I want the output to be:
Small Caps & All Caps
Any ideas?
You can almost do it with:
.link {
text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
text-transform: uppercase;
}
It will give you the output:
Small Caps
All Caps
There is no way to do this with CSS, you could use PHP or Javascript for this.
PHP example:
$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps
jQuery example (it's a plugin now!):
// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
return this.each(function(){
var val = $(this).text(), newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
}
$(this).text(newVal);
});
}
$('a.link').ucwords();​
Convert with JavaScript using .toLowerCase() and capitalize would do the rest.
Interesting question!
capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.
So as far as I can see, this is indeed impossible to do with CSS.
#Harmen shows good-looking PHP and jQuery workarounds in his answer.
I'd like to sugest a pure CSS solution that is more useful than the first letter solution presented but is also very similar.
.link {
text-transform: lowercase;
display: inline-block;
}
.link::first-line {
text-transform: capitalize;
}
<div class="link">HELLO WORLD!</div>
<p class="link">HELLO WORLD!</p>
HELLO WORLD! ( now working! )
Although this is limited to the first line it may be useful for more use cases than the first letter solution since it applies capitalization to the whole line and not only the first word. (all words in the first line)
In the OP's specific case this could have solved it.
Notes: As mentioned in the first letter solution comments, the order of the CSS rules is important! Also note that I changed the <a> tag for a <div> tag because for some reason the pseudo-element ::first-line doesn't work with <a> tags natively but either <div> or <p> are fine.
EDIT: the <a> element will work if display: inline-block; is added to the .link class. Thanks to Dave Land for spotting that!
New Note: if the text wraps it will loose the capitalization because it is now in fact on the second line (first line is still ok).
JavaScript:
var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
links[i].innerHTML = links[i].innerHTML.toLowerCase();
}
CSS:
.link { text-transform: capitalize; }
What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.
captialize only effects the first letter of the word. http://www.w3.org/TR/CSS21/text.html#propdef-text-transform
You can do it with css first-letter!
eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
May be useful for java and jstl.
Initialize variable with localized message.
After that it is possible to use it in jstl toLowerCase function.
Transform with CSS.
In JSP
1.
<fmt:message key="some.key" var="item"/>
2.
<div class="content">
${fn:toLowerCase(item)}
</div>
In CSS
3.
.content {
text-transform:capitalize;
}
If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.
After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:
Follow this code:
Step-1: Call jquery library in html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Step-2: Write code to change text of input fields:
<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
});});
</script>
Step-3: Create HTML input fields with same id's you use in jquery code like:
<input type="text" id="edit-submitted-first-name" name="field name">
The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)
**Result:
Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here.
Result should like this: User Type: "thank you" it will change with "Thank You".
**
Best of luck
The PHP solution, in backend:
$string = 'UPPERCASE';
$lowercase = strtolower($string);
echo ucwords($lowercase);
I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.
Regex solutions are the fastest for sure.
Here is the jsPerf: https://jsperf.com/capitalize-jwaz
There are 2 regex solutions.
The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.
If you only want to capitalize letters that are preceded by a space then use the second regex
/(^[a-z]|\s[a-z])/g
if you are using jQuery; this is one a way to do it:
$('.link').each(function() {
$(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});
Here is an easier to read version doing the same thing:
//Iterate all the elements in jQuery object
$('.link').each(function() {
//get text from element and make it lower-case
var string = $(this).text().toLowerCase();
//set element text to the new string that is lower-case
$(this).text(string);
//set the css to capitalize
$(this).css('text-transform','capitalize');
});
Demo
all wrong it does exist --> font-variant: small-caps;
text-transform:capitalize; just the first letter cap

Resources