Home > Enterprise >  Capitalize first letter of a sentence in a placeholder
Capitalize first letter of a sentence in a placeholder

Time:03-30

Is it possible capitalize only "Date" in this situation without using js?

placeholder="date (dd/mm/yyyy)"

CodePudding user response:

It does not appear we can use the ::first-letter selector on an input to target the placeholder. However, you could achieve a near result using capitalize. See example below.

input::placeholder {
    text-transform: capitalize;
}
<input type="text" placeholder="date (dd/mm/yyyy)" />

However, you could achieve the desired result using some simple JavaScript.

const input = document.querySelector("input")
const placeholder = input.getAttribute("placeholder");              
input.setAttribute('placeholder', placeholder[0].toUpperCase()   placeholder.substring(1));
<input type="text" placeholder="date (dd/mm/yyyy)" />

CodePudding user response:

AFAIK, ::placeholder and :placeholder-shown (an alternative I considered at first), are very limited. The best non-JavaScript solution is to convey information by showing the details in markup by using :focus-within on a <small> like a pop-up (see Example 1 in snippet below -- click the input (focus) and then click elsewhere (unfocus)).

Assuming that the <input> resides within a <form>, one line (albiet a long line), of JavaScript can rectify all [placeholder]s. Add a [name] with a shared value to all applicable <input> and <textarea>s in a <form> then use HTMLFormElement and HTMLFormControlsCollection interface to reference them all (see Example 2 in snippet below).

Note: No solution is as simple as just changing one simple letter in a placeholder by editing the HTML itself. If there's a ton of them or they are dynamically added and you can't control the back-end, then Example 2 is the best solution.

[...document.forms.example2.elements.text] // Collect all [name="text"]
.forEach(text => text.placeholder = // Each [name="text"]["placeholder"] is now
  text.placeholder.charAt(0).toUpperCase() // "D" 
    // AND
  text.placeholder.slice(1)); // "ate dd/mm/yyyy"
/* General CSS */

html {
  font: 2ch/1.15 'Segoe UI'
}

input {
  display: inline-block;
  font: inherit;
  margin-bottom: 5px;
}


/* Example 1 */

.example1 input::placeholder {
  text-transform: capitalize;
}

small {
  opacity: 0;
  transition: 0.5s;
  color: tomato;
}

.example1:focus-within small {
  opacity: 1;
  transition: 0.5s;
}
<fieldset>
  <legend>Example 1</legend>
  <label class='example1'>
    <input placeholder='date*'> 
    <small>*dd/mm/yyyy</small>
  </label>
</fieldset>

<form name='example2'>
  <fieldset>
    <legend>Example 2</legend>
    <input name='text' placeholder='date dd/mm/yyyy'>
    <input name='text' placeholder='enter first name'>
    <textarea name='text' rows='3' cols='48' placeholder='instead of taking the time to capatalize your placeholders properly, use a little JavaScript.'></textarea>
  </fieldset>
</form>

  • Related