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> </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   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
Related
I have a dynamic input boxes having the following ids, points0, points1,points2 etc. I want to make sure that these input boxes shoould match only numbers. So I used the following code but in console it always shows
TypeError: $(...).val(...) is undefined
So I used the following code. I am looping over input text boxes.
var result = document.getElementsByTagName("input");
for (var j = 0; j < result.length; j++) {
var points = 'Enter a valid point.';
var regex = '/^[A-Za-z!##></!?\$%\^\&*\)\(+=._-]+$/g';
if ($("#points" + j).val().match(regex)) {
$('#points' + j + ' + span').html('');
$('#points' + j).after('<span class="' + errTextboxClass + '" style="color:#e03b3b;">' + points + '</span>');
$('#points' + j).focus();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In my Laravel blade I am looping some answers,
#if($ans)
#for($j=0;$j<count($ans) ;$j++)
<input class="form-control " name="points[]" id="points{{$j}}" placeholder="POINTS" value="<?php echo $ans[$j]['points'];?>">
#endfor
#endif
You may want to use a better selector for the input elements. You can use input[id^='points'] for example. This will look for input elements with a the id that starts with points.
Consider the following example:
var results = $("input[id^='points']");
var points = 'Enter a valid point.';
var regex = '/^[A-Za-z!##></!?\$%\^\&*\)\(+=._-]+$/g';
results.each(function(i, el) {
if ($(el).val().match(regex)) {
console.log("Match on #" + $(el).attr("id"));
$(el).next('span').html('');
$("<span>", {
class: "errTextboxClass"
}).css("color", "#e03b3b;").html(points).insertAfter($(el));
$(el).focus();
}
});
Using .each() we can iterate each of the matching elements and test them against the RegEx pattern. You might also consider a different pattern. It looks like you want to allow only numbers, could try:
^[\D]+$
This would match any Non-Digit. If it were me, I would prevent the User from being able to enter non-digits in the field itself using .keypress(). For example:
$(function() {
$("input[id^='points']").keypress(function(e) {
console.log(e.which);
if (e.which !== 46 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
}
});
});
label {
width: 80px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>Points 1</label> <input id="points1" type="text">
</div>
<div>
<label>Points 2</label> <input id="points2" type="text">
</div>
<div>
<label>Name</label> <input id="name1" type="text">
</div>
See More:
Attribute Starts With Selector [name^=”value”]
.next()
RegEx101
Prevent typing non-numeric in input type number
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" />
Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online
I have an HTML header box like so
<textarea name="order[header_comments]"></textarea>
and then I have line comment boxes like so:
<textarea name="line_comments[0][line_comments]"></textarea>
<textarea name="line_comments[1][line_comments]"></textarea>
...
<textarea name="line_comments[n][line_comments]"></textarea>
Line boxes may have some text in them already.
What I want to do is this:
As I type anything in the header box, I want it to be immediately pre-pended to all the line comment boxes. That is all line comment boxes need to at all times have this, even if line boxes are edited, before, or after the header box is filled in:
{real-time header text}{EOL}{any text that was there already}
I assume that if I edit any text in the line boxes, it must not touch the header text (otherwise things will get messed up).
How do I do this?
I can add id for class to the textarea tags as needed. I am not sure which technique to use or how to begin.
My started code:
<textarea name="order[header_comments]" placeholder="header box"></textarea>
<textarea name="line_comments[0][line_comments]"></textarea>
<textarea name="line_comments[1][line_comments]">some existing text</textarea>
I think this is close to what you're describing (with the assumption that the line comments should be unmodifiable).
var previousLength = 0;
$("#headerBox").on('keyup', function() {
var headerVal = $("#headerBox").val();
$('.commentBox').each(function(){
this.value = headerVal + this.value.substring(previousLength, this.value.length);
});
previousLength = headerVal.length;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="headerBox" name="order[header_comments]" placeholder="header box"></textarea>
<textarea readonly class="commentBox" name="line_comments[0][line_comments]"></textarea>
<textarea readonly class="commentBox" name="line_comments[1][line_comments]">some existing text</textarea>
EDIT: This demonstrates "protecting" the prepended header content in the line comments. Attempts to modify the header portion of the line comment will immediately be reverted. It's not perfect, I'm sure some cases aren't accounted for, but hopefully a helpful starting point.
var previousLength = 0;
$("#headerBox").on('keyup', function() {
var headerVal = $("#headerBox").val();
$('.commentBox').each(function(){
this.value = headerVal + this.value.substring(previousLength, this.value.length);
});
previousLength = headerVal.length;
});
var beforeChange = "";
$('.commentBox').on('keydown', function() {
beforeChange = this.value;
});
$('.commentBox').on('keyup', function() {
var headerVal = $("#headerBox").val();
if (!this.value.startsWith(headerVal)){
this.value = beforeChange;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="headerBox" name="order[header_comments]" placeholder="header box"></textarea>
<textarea class="commentBox" name="line_comments[0][line_comments]"></textarea>
<textarea class="commentBox" name="line_comments[1][line_comments]">some existing text</textarea>
You can use something like this:
var prevPrincipalVal = "";
$("#principal").keyup(function(){
var principalVal = $(this).val();
$(".other").each(function(){
$(this).val($(this).val().replace(new RegExp("^" + prevPrincipalVal + "\n*"), principalVal + "\n"));
})
prevPrincipalVal = principalVal;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="principal"></textarea>
<textarea class="other">Custom 1</textarea>
<textarea class="other">Custom 2</textarea>
<textarea class="other">Custom 3</textarea>
The basic idea is to save the previous value of the principal <textarea> and replace the previous value with the new one in each of the other <textarea>s. These needs perfecting, you'll have to escape all special regex character from the text of the principal <textarea>.
See below if this is what you want
$(document).ready(function() {
$("textarea[name='order[header_comments]']").on('keyup', function(e) {
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
//console.log(String.fromCharCode(keynum));
let headerVal = String.fromCharCode(keynum);
$("textarea[name*='line_comments']").each(function() {
$(this).val($(this).val() + headerVal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="order[header_comments]" placeholder="header box"></textarea>
<textarea name="line_comments[0][line_comments]"></textarea>
<textarea name="line_comments[1][line_comments]">some existing text</textarea>
$('input[order[header_comments]]').change(function(){
var headText = $(this).val() ;
$("textarea[name*='line_comments']").each(function() {
$(this).val(headText + ' ' + $(this).val());
});
});
I have seen in a few "username" fields where you type in a username, and below it, in something like a span, it will append it to a url. A lot like what is happening as I type this in StackOverflow at the bottom.
I would like to show only allowed characters from a list, ignore any input of characters not in that list.
I am really new to JS. In this case, I am using Jquery, and have a sort of works with some parts, and other parts I do not, or I have not gotten there yet.
Desire:
Input form field accepts only characters from a list, others are ignored.
Get the new key as entered, and append it to an element.
Here is the mess I have so far:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
In the html I have:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />
Why not use a regular exprsession to replace non alphanumeric characters?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
Looking at your comments, you have some confusion over the different Key events:
keyup (and keydown) tell you which physical key has been pressed, while keypress will tell you which character has been typed - which is why you're always getting uppercase letters from fromCharCode.
I'm using something like this to sort out urls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keypress(function(e) {
var entered = $('#cart-name').val();
// Regular Express to perform match on all alphanumeric characters,
// and - and _
var matchPattern = /[\w/_/-]/g;
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
if (entered_char.match(matchPattern)) {
$('#live').text(entered + entered_char);
}
else if (enteredKey == " ") {
// Replace spaces with hyphens for SEO
$('#live').text(entered + "-");
}
});
});
</script>
Should see you right.