While Typing in a input First letter should change to Capital, But rest letters should be in lowercase, Even user Input capital letters it should changed it lowercase.
Example input word: mOuSe , ComPuTER
Important Point: While Typing it should change to: Mouse, Computer
I have tried many Stackflow soloution, But for above logic i found none.
Using Css: Click Here
Using Javacript: Click Here (This one worked but for last letter it doesnt works)
Any solution is accepted using Jquery, Javascript or Css
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
使用input
事件而不是keypress
事件。
$('input').on('input', function(event) {
function initCap(t){
t.value=t.value.toLowerCase();
t.style='text-transform:capitalize;'
}
call the method onkeypress and onblur
Try This
$('input').on('keyup', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
$('input').on('keydown', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
It might be interesting to point out that CSS text-transform: capitalize;
only alters the display of the input, while Javascript modifies the actual HTML value . This matters if the input is, for example, a CAPTCHA response or form input field that needs to be validated.
With pure Javascript, you could split the input into separate words & transform each one of them, like so:
HTML
<div id="transform">mOuSE, cOmPUTEr</div>
<button type="button">Capitalize</button>
JS
var rgx = /,/; /* word splitter, can be anything */
var target = document.getElementById('transform');
document.getElementsByTagName('button')[0].onclick = function() {
var strArr = target.innerHTML.split(rgx); /* split the input */
for (var word = 0; word < strArr.length; word++) { /* iterate over each word */
strArr[word] = strArr[word].toLowerCase().trim();
var firstLetter = strArr[word].substr(0,1).toUpperCase();
var otherLetters = strArr[word].substr(1, strArr[word].length)
strArr[word] = firstLetter+otherLetters;
}
target.innerHTML = strArr.join();
}
Demo: http://jsbin.com/farib/2/edit
NB: If your input is in a <textarea>
or <input>
, replace .innerHTML
with .value
.
Try this css solution.
input {
text-transform:capitalize;
color: blue;
}
$(document).ready(function(){
$("input").on("keypress",function(){
$(this).val($(this).val().toLowerCase());
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.