Capitalize first letter of string on keydown input - javascript

I want to change the first letter to Uppercase when I write on the textbox.
I wrote the below code but it changes the letter in style of css and when I send it with form it send it with small word at first.
how can i transform to capitalize in jquery?
here is my code :
$('.capital').css('textTransform', 'capitalize');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" value="" class="capital"/>

Use toUpperCase and substr to get 1st letter and make it upper case.
$(".capital").focusout(function() {
var yourtext = $(this).val();
alert(yourtext.substr(0, 1).toUpperCase() + yourtext.substr(1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" value="" class="capital"/>

This code always changes the first letter to uppercase. I think it's bad design to do so.
var firstCapitalAlways= function (event) {
var val = $(event.target).val();
var firstLetterUpper = val[0] ? val[0].toUpperCase() : "";
$(event.target).val(firstLetterUpper + val.substr(1, val.length));
}
var firstCapitalOnBlur = function(event) {
var val = $(event.target).val();
if(val){
$(event.target).val(val[0].toUpperCase() + val.substr(0, val.length))
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Always</label>
<input type="text" value="" onkeyup="firstCapitalAlways(event);" class="capital"/>
<label>Onblur</label>
<input type="text" value="" onblur="firstCapitalOnBlur(event);" class="capital"/>

Related

convert a text to url with dash

Check the code below. Now if I put some text in pTitle and when I press space from the keyboard it makes a - clone dash between words I typed. But the problem is after I press next word previous - dash removes also between - and word it also makes an auto space which I don't want. Now tell me how can I fix the - auto remove issue? Any advice? also, a fiddle link attached for a quick check
Html:
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
Jq code:
$('#pTitle').keyup(function (e) {
if (e.keyCode === 32) {
$('#pUrl').val($(this).val()+'-');
} else {
$('#pUrl').val($(this).val());
}
var charNumber = e.currentTarget.value.length;
if (charNumber === 0) {
$('#pUrl').val('#');
}
});
You can use a .replace() to swap the spaces for hyphens. The ternary equation allows the url to be "#" of the length of the input value == 0 (for example if you have text entered and then delete all characters) or the hyphenated text if there is text in the input.
$('#pTitle').keyup(function (e) {
var newVal = $(this).val();
newVal.length == 0
? $('#pUrl').val('#')
: $('#pUrl').val(newVal.replace(/ /g,'-'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
A nice solution is provided by #gavgrif above.
If you want to avoid regex, then here's a non regex solution
$('#pTitle').keyup(function (e) {
var val = $(this).val();
val.length==0
? $('#pUrl').val('#')
: $('#pUrl').val(val.split(" ").join("-"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
You can simply read the text from pTitle input and replace space by dash character '-' and set the result into pUrl input
$('#pTitle').keyup(function (e) {
$('#pUrl').val($(this).val().replace(/ /g,'-'));
var charNumber = e.currentTarget.value.length;
if (charNumber === 0) {
$('#pUrl').val('#');
}
});

How to count the number of commas in a text box using javascript or jquery?

Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. I can use javascript, jquery and/or regex here.
What code should I place within this function?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated.
I use regex to find the number of times the string , occurs in the textbox value. It prints whether or not it is valid (having less than 5 commas).
$("#validate").click(function () {
console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" />
<button id="validate">less than 5 commas?</button>
Automatically responding to user input
In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input event.
$("#textboxInfo").on('input', function () {
var isValid = ($(this).val().match(/,/g) || []).length < 5;
$(".isValid").html(isValid ? "Valid" : "Invalid");
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" value="I really love ,,, commas!" />
<div class="isValid"> </div>
Split the value of the input box and filter out , and check the length of it
$('.submit-btn').on("click", function() {
var getNumbers = $('#testBox').val().split('').filter(function(item) {
return item === ','
}).length;
console.log(getNumbers)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='testBox'>
<button class='submit-btn' type="button">Click</button>
You could try using this Comma Counter
$('button').on('click',function(){
var counter = ($('div').html().match(/,/g) || []).length;
$('.result').text(counter);
}
)/
You could also remove everything that is not a comma [^,], replace that with an empty string and count the length of the string.
$('.submit-btn').on("click", function() {
var nr = $("#tbx").val().replace(/[^,]/g, "").length;
console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='tbx'>
<button class='submit-btn' type="button">Click</button>

Is it possible to get only the first letter of what is written in the input?

I want to get only the first letter of what is written in the input. Can help me?
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
<script type="text/javascript">
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data;
}
</script>
Yes you can split the variable data as an array:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value[0];
document.getElementById(text1Id).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Use [number] to get the value at some point.
Or you could use the slice() function:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data.slice(0,1);
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Or as suggested in the other answer charAt().
Use charAt(0) to get the first character:
function copyText(inputId,displayId) {
var data = document.getElementById(inputId).value;
var firstLetter = data.charAt(0);
document.getElementById(displayId).innerHTML = "The first letter is: " + firstLetter;
}
<label for ="texte">Type your name here</label>
<input id="texte" type="text" onkeyup="copyText('texte','text')">
<p id="text"></p>
function copyText( texteId, text1Id ) {
var d = document;
d.g = d.getElementById;
var data = d.g( texteId ).value[0];
d.g( text1Id ).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
In JavaScript you may treat a string as if it were an array. So by specifying the zeroeth index of value, the code grabs the first letter and that becomes the content of the div with the id of "text" using that element's innerHTML property.
const input = document.querySelector('#texte');
const text = document.querySelector('#text');
// keydown and keyup are alternate events
input.addEventListener('input', function() {
text.innerHTML = this.value[0];
});

Allow only number digits in input type regex. issue is i am able to type this(1.) , want to prevent it

MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.

Set format for decimal number

I am validating certain input by using RegEx in jQuery which is working as expected. I want to add an addition where it adds 0 prior to decimal point if user don't add it.
For example,
.50 to 0.50
-.50 to -0.50
How to do that?
Code:
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
Change [0-9]+ to [0-9]*, so that it allows zero digits instead of requireing at least one.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]*([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
You can fix the value like this if you need to convert it later:
if(currentSetTextBoxValue.indexOf('.') === 0){
currentSetTextBoxValue = '0' + currentSetTextBoxValue;
}
if(currentSetTextBoxValue.indexOf('.') === 1 && currentSetTextBoxValue.indexOf('-') === 0){
currentSetTextBoxValue = '-0.' + currentSetTextBoxValue.split('.')[1];
}
https://jsfiddle.net/str59woa/3/
You can replace the input using regex! This regex looks for . or -. at the beginning of the string and it will replace it by 0. or -0. depending on what it found, if it does not match the string will be the same.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val().replace(/^(\-)?\./, "$10.");
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
https://jsfiddle.net/punsm9o0/1/

Categories