How to make in input the first letter capitalized? [duplicate] - javascript

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 3 years ago.
How to make in input the first letter capitalized? Css method text-transform: capitalize; does not fit.
var positions = $('ul li');
var inputSearch = $('input');
inputSearch.val('').on('input', function(e){
var terms = this.value.toLowerCase().split(/[\s,.]+/);
positions.each(function(){
var text = this.innerText.toLowerCase();
this.hidden = !terms.every(function(term){
return text.indexOf(term) !== -1;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="placeholder">
<ul>
<li>wrew</li>
<li>w</li>
<li>rew</li>
</ul>

$('ul li').each(function(index, elem){
var text = $(elem).text();
text = text.charAt(0).toUpperCase() + text.slice(1);
$(elem).text(text);
});

You can use the code below. This code will track when you press the key, and when you do, it'll get the current value of the input (before the key you pressed is added). It would then check if the last character in the input field is a space. If it is, it'll add to text the key you just pressed, but uppercase. If not, it'll simply add the key you just pressed to text
Then, the next time you press any key, the value of the input would change the the value of text, which would have the first letter of every word capitalized.
var text = "";
var val;
$(".input").keypress(function(e) {
val = $(this).val();
if (val[val.length - 1] == ' ') {
text += e.key.toUpperCase();
}
else {
text += e.key;
}
});
$(".input").keydown(function() {
$(this).val(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Placeholder" class="input" />

Related

Taking only first string from paste value in input value [duplicate]

This question already has answers here:
Get first word of string
(12 answers)
Closed 1 year ago.
I want to get only the first value from copy-paste value.
For example:
my copy text is: Lorem Lipsum Test
So when I copied this above text and paste it into the HTML input filed there need to come only "Lorem" I don't need other text
Is there any way to achieve these things?
Thanks in advance.
it only returns always the first word from string input and you have to clear for copy new value then it's show first word of the new copied string.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#getfirstword").on("keyup", function(e) {
debugger
// do stuff!
var str = $(this).val();
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
var firstWord ="";
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
firstWord = str1[i].split(' ')[0];
}
$("#input1").val(firstWord);
})
});
</script>
</head>
<body>
<input id="getfirstword" />
<input id="input1" disabled/>
</body>
</html>
You can add an input event to see what you are trying to add to your element. This code will split your pasted text and only add the first word.
const input = document.querySelector('input');
const log = document.getElementById('values');
input.addEventListener('input', updateValue);
var previousValue = "";
function updateValue(e) {
log.textContent = e.data;
if (e.data && e.inputType == "insertFromPaste") {
if (e.data.length > 1) {
let val = e.data.split(" ")[0];
let str = previousValue + val;
e.target.value = str;
}
}
previousValue = e.target.value;
}
<input placeholder="Enter some text" name="name"/>
<p id="values"></p>

Get value from input box with js [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 5 years ago.
I have no idea how to get value from input box. Right now when I click BET button it just subtracts 100, I want to achieve so when I enter the value in the text box and hit bet it'll subtract the value which I've entered from the balance. Here is my code:
HTML:
<div>
<input type="text" value=0 name="betAmount">
<button class="betBTN">BET</button>
</div>
JS:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('.betBTN').addEventListener('click', function() {
var toAdd = document.querySelector('div').textContent - 100;
document.querySelector('div').innerHTML = "";
document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
});
});
Any suggestions?
Replace your 100 with
document.querySelector("input").value;
This line will get the value of input element
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('.betBTN').addEventListener('click', function() {
var toAdd = document.querySelector('div').textContent - document.querySelector("input").value;
document.querySelector('div').innerHTML = "";
document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd);
});
});
Balance: <div>1000</div>
<input type="text" value=0 name="betAmount">
<button class="betBTN">BET</button>
If you’re talking about the entered value, then the following would do the job:
document.querySelector('input[name="betAmount"]').value;
All input elements, whether they are HTML input or textarea or select etc have a value property which is the actual value of the user data.

Insert blank space between two words in html

I wan to insert some spaces in between two words and I do not want to use pre tags. In my code here is one input field where user can enter text and some javascript code display it in div you can check the code right below.
<input type="text" id="user-input" />
<div id="user-text"></div>
Javascript code
$(document).on('keyup', '#user-input', function(event){
var userText = $('#user-text');
var clientText = $(this).val().toUpperCase();
if(event.keyCode === 32 || event.which === 32){ clientText += ' '; }
clientText = $('<textarea />').html(clientText).text();
userText.text(clientText);
});
I'm using for inserting space between two words but this is not working. It only insert one space if I want to insert ten space then what.
The code is not working like as I'm expecting you can't able to insert more than one space using this code.
UPDATE
I want like this.
You can insert more than one to text and it will be displayed correctly. Simple white-spaces are truncated to single.
$(document).ready(function () {
$('input').on('input change', function () {
$('#span1').html(
$(this).val() + ' '.repeat($(this).val().length)
);
$('#span2').html(
$(this).val() + ' '.repeat($(this).val().length)
);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Some text"/><br/>
<span id='span1'>Some text</span>Other text to pad with <b>&nbsp;</b>.<br/>
<span id='span2'>Some text</span>Other text to pad with <b>white-space</b>.
To preserve user entered white spaces:
$(document).ready(function() {
$('input').on('input change', function() {
$('span').html(
$(this).val().toUpperCase().replace(/\s/g, ' ')
);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<br/>
<span></span>
If you really want to insert say 10 spaces, then you have to put &nbsp 10 times.
clientText += ' ';
You can learn more about HTML entities related to spaces here.
I have created a simple convertSpace function to take care of converting blank spaces to nbsp. https://jsfiddle.net/elemilion/6own3g7z/
function convertSpacesToNbsp(str){
return str.split('').map(function(char){
if(char === ' '){
char = ' ';
}
return char;
}).join('');
}
$(document).on('keyup', '#user-input', function(event){
var userText = $('#user-text');
var inputStr = $(this).val().toUpperCase();
var clientText = convertSpacesToNbsp(inputStr);
userText.html(clientText);
});
you can use replace() just replace all the \s equivalent space to nbsp;
var userText = $('#user-text');
$(document).on('input', '#user-input', function(event){
userText.html( $(this).val().replace(/\s/g,' ') );
});
DEMO

Pasting multiple numbers over multiple input fields

I've got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they'll get the 6 digit code and it would be ideal to allow them to simply copy the 6 digit code we send them into these input fields by simply putting pasting into the first input field and having the remaining 5 digits go into the remaining 5 input fields. It would just make it much easier than having to manually enter each digit into each input field.
Here's the code we're currently using, but it can easily be changed to accomplish what is described above:
<input type="text" maxlength="1" class="def-txt-input" name="chars[1]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[2]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[3]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[4]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[5]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[6]">
I saw a posting similar to this here: Pasting of serialnumber over multiple textfields
But it doesn't have the solution I'm looking for. Ideally this could be pulled off using jQuery or plain JavaScript.
Edit
I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.
After looking at this for a while I added a solution which uses a hybrid between the 2.
The code seems to do all that is required now.
The Script:
var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
// Prevents user from manually entering non-digits.
$inputs.on("input.fromManual", function(){
if(!intRegex.test($(this).val())){
$(this).val("");
}
});
// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
$inputs.on("paste", function() {
var $this = $(this);
var originalValue = $this.val();
$this.val("");
$this.one("input.fromPaste", function(){
$currentInputBox = $(this);
var pastedValue = $currentInputBox.val();
if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
pasteValues(pastedValue);
}
else {
$this.val(originalValue);
}
$inputs.attr("maxlength", 1);
});
$inputs.attr("maxlength", 6);
});
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
var values = element.split("");
$(values).each(function(index) {
var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
$inputBox.val(values[index])
});
};​
See DEMO
Here is an example of a jquery plugin that does the same thing as the original answer only generalized.
I went to great lengths to modify the original answer ( http://jsfiddle.net/D7jVR/ ) to a jquery plugin and the source code is here: https://github.com/relipse/jquery-pastehopacross/blob/master/jquery.pastehopacross.js
An example of this on jsfiddle is here:
http://jsfiddle.net/D7jVR/111/
The source as of 4-Apr-2013 is below:
/**
* PasteHopAcross jquery plugin
* Paste across multiple inputs plugin,
* inspired by http://jsfiddle.net/D7jVR/
*/
(function ($) {
jQuery.fn.pastehopacross = function(opts){
if (!opts){ opts = {} }
if (!opts.regexRemove){
opts.regexRemove = false;
}
if (!opts.inputs){
opts.inputs = [];
}
if (opts.inputs.length == 0){
//return
return $(this);
}
if (!opts.first_maxlength){
opts.first_maxlength = $(this).attr('maxlength');
if (!opts.first_maxlength){
return $(this);
}
}
$(this).on('paste', function(){
//remove maxlength attribute
$(this).removeAttr('maxlength');
$(this).one("input.fromPaste", function(){
var $firstBox = $(this);
var pastedValue = $(this).val();
if (opts.regexRemove){
pastedValue = pastedValue.replace(opts.regexRemove, "");
}
var str_pv = pastedValue;
$(opts.inputs).each(function(){
var pv = str_pv.split('');
var maxlength;
if ($firstBox.get(0) == this){
maxlength = opts.first_maxlength;
}else{
maxlength = $(this).attr('maxlength');
}
if (maxlength == undefined){
//paste them all!
maxlength = pv.length;
}
//clear the value
$(this).val('');
var nwval = '';
for (var i = 0; i < maxlength; ++i){
if (typeof(pv[i]) != 'undefined'){
nwval += pv[i];
}
}
$(this).val(nwval);
//remove everything from earlier
str_pv = str_pv.substring(maxlength);
});
//restore maxlength attribute
$(this).attr('maxlength', opts.first_maxlength);
});
});
return $(this);
}
})(jQuery);
This shouldn't be too difficult ... add a handler for the paste event on the first input, and then process per the requirement.
Edit
Actually this is much trickier than I thought, because it seems there's no way to get what text was pasted. You might have to kind of hack this functionality in, using something like this (semi-working)... (see the JSFiddle).
$(document).on("input", "input[name^=chars]", function(e) {
// get the text entered
var text = $(this).val();
// if 6 characters were entered, place one in each of the input textboxes
if (text.length == 6) {
for (i=1 ; i<=text.length ; i++) {
$("input[name^=chars]").eq(i-1).val(text[i-1]);
}
}
// otherwise, make sure a maximum of 1 character can be entered
else if (text.length > 1) {
$(this).val(text[0]);
}
});
HTML
<input id="input-1" maxlength="1" type="number" />
<input id="input-2" maxlength="1" type="number" />
<input id="input-3" maxlength="1" type="number" />
<input id="input-4" maxlength="1" type="number" />
jQuery
$("input").bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text');
var num_array = [];
num_array = pastedData.toString(10).replace(/\D/g, '0').split('').map(Number); // creates array of numbers
for(var a = 0; a < 4; a++) { // Since I have 4 input boxes to fill in
var pos = a+1;
event.preventDefault();
$('#input-'+pos).val(num_array[a]);
}
});
You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.
As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.
Here is one possible solution:
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup paste', handleCharacter)
.on('keydown', handleBackspace);
I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

Populating a textarea from several textfields

I have several textfields which will populate a text area.
I managed to populate it with a javascript function. On the onblur event of a textfield, the value of the textfield is passed and the textarea is field with this value.
However, my problem is the following:
If I modify a previously filled textfield, the textarea will simply append it again.
What I need is some functionality that if:
1: If I give focus to the textfield which is already been filled and I don't modify it, it will not be appended (I implemented this with an if statement and substring.
2: If I modify a previously filled textfield, the text area DOES NOT append it again at the end of the string BUT it replaces the part of the textarea with just that text field new value.
Take for instance the following 2 textfields:
<input type="text" id="txtName" name="txtName" />
<input type="text" id="txtSurname" name="txtSurname" />
If I fill up these textfields with John and Doe respectively, the textarea value will become:
txtName=John,txtSurname="Doe"
I managed to implement this.
What I need is that if I edit txtName from John to Alex, the textarea value will be as follows:
txtName=Alex,txtSurname=Doe
and not like is currently being displayed, i.e.
txtName=John,txtSurname=Doe,txtName=Alex
Should I achieve this by using an array which will store all the textfields values?
Any help would be greatly appreciated.
Many thanks in advance.
the following code should work for you. I have wrapped the textboxes inside a div. and also registered a onkeyup event on both the textboxes.
The javascript code iterates through each textboxe inside the div, and prints its name and value in the textarea.
HTML
<div id="textBoxContainer">
<input type="text" id="txtName" onkeyup="UpdateTextArea();" name="txtName" />
<input type="text" id="txtSurname" onkeyup="UpdateTextArea();" name="txtSurname" />
</div>
<textarea id="textAreaResult"></textarea>
Javascript
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + ",";
}
textAreaFinalResult.value = finalResult;
}
</script>
Hope this Helps! :)
For the record, I feel like this code is an ugly hack, but it should do the trick...
var fieldName = "txtName"; //your field name
var newValue = "Alex"; //your new value
var value = document.getElementById("my-textarea").value;
value = "," + value; //add a comma so we can ensure we don't replace the wrong value where the fieldname is a substring of another fieldname
if(value.indexOf("," + fieldName + "=") > 0) //see if a value is already defined
{
var index = value.indexOf("," + fieldName + "=") + fieldName.length + 2;
var start = value.substring(0, index); //get the portion before the value
var end = value.substring(index); //get everything else
if(end.indexOf(",") > 0)
{
end = end.substring(end.indexOf(",")); //remove the value by reducing the end to the location of the next comma
}else{
end = ""; //if there isn't another comma it was the last value in the list, so set the new end to nothing
}
value = start + newValue + end;
value = value.substring(1); //remove the starting comma we gave it
document.getElementById("my-textarea").value = value;
}else{
//append it to the end as you are already doing
}

Categories

Resources