I was wondering how can i automatically make first character of the word in an input area
Currently my code is
Name:<input type='text' name='name' class='name' placeholder='Enter your name here'/>
You can try this: DEMO
Name:<input type='text' name='name' class='name' style="text-transform: capitalize;" placeholder='Enter your name here'/>
or add text-transform: capitalize; in your name in css.
The problem with using CSS (text-transform: capitalize) is that when the form gets submitted, the name will be submitted with a lowercase name.
The CSS works well for cosmetics but not for functionality.
You can use jQuery to force capitalization functionality in your input boxes:
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$('.name').keyup(function(event) {
var textBox = event.target;
var start = textBox.selectionStart;
var end = textBox.selectionEnd;
textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1).toLowerCase();
textBox.setSelectionRange(start, end);
});
});
</script>
Put this code between the <head> </head> on the page where your form is located.
Above jQuery will also force ALL CAPS to Capitalize.
Check out the Fiddle here: https://jsfiddle.net/cgaybba/6rps8hfo/
I think it should also be mentioned that if the form is on mobile, you can just use the autocapitalize attribute. see here for documentation
Try this
HTML CODE
<input type='text' name='name' class='name' placeholder='Enter your name here'/>
CSS CODE
<style>
.name
{
text-transform:capitalize;
}
</style>
Update you css
.name { text-transform: capitalize; }
The good side of using JS is that when the user submits the form, it retains the capitalized input values, but using css when the form is submitted, it looses the capitalized values (for frontend only).
Note for CSS: make sure you don't have any overriding styles else use !important.
//For CSS
input { text-transform: capitalize }
//For JS
$('.your-input').on('change keydown paste', function(e) {
if (this.value.length = 1) {}
var $this_val = $(this).val();
this_val = $this_val.toLowerCase().replace(/\b[a-z]/g, function(char) {
return char.toUpperCase();
});
$(this).val(this_val);
});
Just include → style="text-transform:capitalize;" inside your input tag.
Related
I am trying to create an HTML form is separate parts for layout reasons. As far as I understand, you can use a fieldset with a form attribute to associate the fieldset with the form, even if it’s not inside the form (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset).
However, if I have a separate fieldset with a submit button or another input in it, it doesn’t seem to work.
<form id="test">
<input name="inside-stuff" value="Inside">
<button type="submit">Doit Inside</button>
</form>
<fieldset form="test">
<input name="outside-stuff" value="Outside">
<button type="submit">Doit Outside</button>
</fieldset>
In the above snippet I have two submit buttons and two inputs. The one in the actual form works, while the one in the attached fieldset doesn’t. When I use the inside submit button, it only submits what’s in side the main form, not what is in the associated fieldset.
This may not be obvious when running the snippet, but is certainly the case when tried in real life.
What is missing to make this work?
Update 1
The problem appears to be more generic than that. I find that input elements inside an associated fieldset don’t get submitted either.
Update 2
This is not a duplicate of Submit form using a button outside the <form> tag. This question specifically refers to a fieldset element. The other doesn’t even mention it.
I wrote the following javascript
function control() {
function view(i) {
var frm = items[i].getAttribute("form");
var fBase = document.querySelector("form[id=" + frm + "]");
fBase.addEventListener("submit", function(){
var fld = document.querySelector("fieldset[form='" + this.id + "']");
var cln = fld.cloneNode(true);
cln.style.display = "none";
document.getElementById(frm).appendChild(cln);
},true);
}
var items = document.querySelectorAll("FIELDSET[form]");
var getter = function () {
return this.getAttribute("form");
};
for(var i = 0; i < items.length; i++) {
view(i);
Object.defineProperty(items[i], 'form', {
get: getter
});
}
}
window.addEventListener("load",control,true);
It's happening because the Form you have placed inside the fieldset is wrong. The form should be the parent of the fieldset in order to get it to work!
The form tag should always be the parent of the fieldset.
If you place <form> and <fieldset> then it will work. The code below should do.
<form id="test">
<input name="stuff">
<button type="submit">Doit</button>
</form>
<form>
<fieldset>
<input type="text" name="stuff2">
<button type="submit">Doit</button>
</fieldset>
</form>
I hope this will help!
I am trying to make the first character in a input field uppercase.
So far I have tried:
input:first-letter {text-transform:capitalize !important}
input:first-letter {text-transform:uppercase !important}
I have also tried to make the input field styled display:block; and display:inline-block; but with no luck.
I am using the latest version of chrome. If I look in the inspector the
input:first-letter {text-transform:capitalize !important} is flagged to be active but it does not work.
I am open to any Jquery solutions as well
Thanks,
:first-letter wont work on input field. but it works without that.
So change it as input {text-transform:capitalize;} it works fine.
see demo
it works fine without !important
input {text-transform:capitalize;}
<input/>
As you have mentioned in pure css way i have added the above method
Limitation: It will capitalize all words in the input box. In pure CSS it is not possible to capitalize only the first word as of now. you have to try the jquery way to do this as given below
Using jquery:-
using keyup event
$('input').keyup(function(){
if($(this).val().length>0){
var character = $(this).val().charAt(0);
if(character!=character.toUpperCase()){
$(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>
To work even on mouse events:- (like cut paste in mouse)
Using propertychange event by $('input').bind('input propertychange', function() {
$('input').bind('input propertychange', function() {
if($(this).val().length>0){
var character = $(this).val().charAt(0);
if(character!=character.toUpperCase()){
$(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>
You could use an onKeypress listener and capitalize the first character of the value. Keep in mind this function will run every time a key is pressed in that input
$( "#keypress" ).keypress(function() {
var val = $(this).val();
val = val.substr(0, 1).toUpperCase() + val.substr(1);
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="keypress">
For text output, you can easily make only the first character uppercase by css.
.mytable td {
text-transform:lowercase;
}
.mytable td:first-letter {
text-transform:uppercase;
}
how to transfer the uppercase letter to lowercase letter ?.
for example : THIS IS IS A LETTER to lowercase like This is a letter .
I do not want to change the full sentence ,just change except first letter rest all are want to change.
p:first-letter {
text-transform: capitalize;
}
<p>i am devat karetha</p>
I've always used a simple javascript function for cross-browser functionality - this works anywhere:
function sentenceCase(S) //1st upper,rest lower - S=string
{
if (!S) S="";
return S.substr(0,1).toUpperCase() + S.substr(1).toLowerCase();
}
In HTML, try this,
T<div style = "text-transform: lowercase"> IS A LETTER</div>
You could use a quick javascript function:
If this is an HTML form (so naive):
<input type="text" id="test"><input type="button" id="ok">
You could use the following function:
document.getElementById('ok').onclick = function() {
var first = document.getElementById('test').value.substr(0,1);
var rest= document.getElementById('test').value.substr(1);
document.getElementById('test').value = first.toUpperCase() + rest.toLowerCase();
}
The second example works "live" during insertion:
HTML
<input type="text" id="test">
JS
document.getElementById('test').onkeyup = function() {
this.value = this.value.substr(0,1).toUpperCase() + this.value.substr(1).toLowerCase();
}
Get a live preview: jsfiddle.net
Notice how you definitely should do it using two substrings (using substr(start[, end]) method), because to date there are only toUpperCase() and toLowerCase() methods for JS strings;
a toSentenceCase() would be handy in this case, but for what I know it does not exist...
I would like to insert a descriptive text inside an input element that disappers when the user click on it.
I know it is a very common trick, but I do not know how to do that..
What is the simplest/better solution?
If you're using HTML5, you can use the placeholder attribute.
<input type="text" name="user" placeholder="Username">
<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">
A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.
In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.
It's easy to implement and degrades nicely for screen readers and users with no javascript.
Take a look at the two examples here:
http://attardi.org/labels/
I usually use the second method (labels2) on my forms.
The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:
Relatively position a div that contains the input and label
Absolutely position the label
Absolutely position the input on top of the label
Remove the borders of the input and set its background-color to transparent
Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.
I've put together solutions proposed by
#Cory Walker with the extensions from #Rafael
and the one form #Tex witch was a bit complicated for me
and came up with a solution that is hopefully
error-proof with javascript and CSS disabled.
It manipulates with the background-color of the form field to show/hide the label.
<head>
<style type="text/css">
<!--
input {position:relative;background:transparent;}
-->
</style>
<script>
function labelPosition() {
document.getElementById("name").style.position="absolute";
// label is moved behind the textfield using the script,
// so it doesnt apply when javascript disabled
}
</script>
</head>
<body onload="labelPosition()">
<form>
<label id="name">Your name</label>
<input type="text" onblur="if(this.value==''){this.style.background='transparent';}" onfocus="this.style.background='white'">
</form>
</body>
View the script in action: http://mattr.co.uk/work/form_label.html
<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">
Add an onblur event too.
When you start typing it will disappear.If empty it will appear again.
<%= f.text_field :user_email,:value=>"",:placeholder => "Eg:abc#gmail.com"%>
Simplest way...
Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers
http://jamesallardice.github.io/Placeholders.js/
One hint about HTML property placeholder and the tag textarea, please make sure there is no any space between <textarea> and </textarea>, otherwise the placeholder doesn't work, for example:
<textarea id="inputJSON" spellcheck="false" placeholder="JSON response string" style="flex: 1;"> </textarea>
This won't work, because there is a space between...
use this
style:
<style type="text/css">
.defaultLabel_on { color:#0F0; }
.defaultLabel_off { color:#CCC; }
</style>
html:
javascript:
function defaultLabelClean() {
inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].value == inputs[i].getAttribute("innerLabel")) {
inputs[i].value = '';
}
}
}
function defaultLabelAttachEvents(element, label) {
element.setAttribute("innerLabel", label);
element.onfocus = function(e) {
if (this.value==label) {
this.className = 'defaultLabel_on';
this.value = '';
}
}
element.onblur = function(e) {
if (this.value=='') {
this.className = 'defaultLabel_off';
this.value = element.getAttribute("innerLabel");
}
}
if (element.value=='') {
element.className = 'defaultLabel_off';
element.value = element.getAttribute("innerLabel");
}
}
defaultLabelAttachEvents(document.getElementById('MYID'), "MYLABEL");
Just remember to call defaultLabelClean() function before submit form.
good work
You do not need a Javascript code for that...
I think you mean the placeholder attribute. Here is the code:
<input type="text" placeholder="Your descriptive text goes here...">
The default text will be grey-ish and when clicked, it will dissapear!
I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here:
https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/
Here example with Label inside Input fields:
codepen.io/jdax/pen/mEBJNa
Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
<meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<style type="text/css" >
input.searcher
{
background-image: url(/images/search_back.png);
background-repeat: no-repeat;
background-attachment: scroll;
background-x-position: left;
background-y-position: center;
}
</style>
<script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
<input type="text" id="q" name="q" value="" />
<script type="text/javascript" language="JavaScript" >
// <![CDATA[
function f(e){
$('q').removeClassName('searcher');
}
function b(e){
if ( $F('q') == '' )
{
$('q').addClassName('searcher');
}
}
Event.observe( 'q', 'focus', f);
Event.observe( 'q', 'blur', b);
Event.observe( window, 'load', b);
// ]]>
</script>
</body>
</html>
In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.