remove extra comma at the end of the line - javascript

I am working on limiting tags so max will be 5 but for this test I will use 2 however, at the end of the line there is an extra comma left when attempting to add another tag more than the max-allowable. How do I remove that comma?
<body>
<input id="input" type="text" />
</body>
$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 2){
//alert("Hey! That's more than 5 words!");
e.preventDefault();
}
});
DEMO: http://jsfiddle.net/BzN5W/2/

Here, try this :
$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 5){
alert("Hey! That's more than 5 words!");
$('#input').val($('#input').val().substring(0, $('#input').val().length-1));
e.preventDefault();
}
});

$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 5){
$(this).val(value.slice(0,value.length-1))
e.preventDefault();
}
});

Try this:
$("#input").keydown(function(e){
if(e.which === 188 && ($(this).val().match(/,/g) || []).length ==4){
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="input" type="text" />
</body>

Related

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

Disallow special characters in textbox validation

I have javascript code where the validation does not allow more than 20 characters in text box. But, I also want to disallow in special characters in the validation; how can this be accomplished.
Here is my current validation code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js">
/script>
<script type='text/javascript'>
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var len = desc.length;
if (desc.length >= 10)
{
this.value = this.value.substring(0, 10);
} $('#spntxt').text(10 - len + ' Characters Left');
});
}); </script>
try bellow script this will not allow special charter # $ % ^ & * ( )
function validate() {
var element = document.getElementById('input-field');
element.value = element.value.replace(/[^a-zA-Z0-9#]+/, '');
};
<input type="text" id="input-field" onkeyup="validate();"/>
I just use your codes and modify:
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var lastChar = desc.slice(-1);
var spc = !((lastChar.charCodeAt()>=48&&lastChar.charCodeAt()<=57)||(lastChar.charCodeAt()>=65&&lastChar.charCodeAt()<=90)||(lastChar.charCodeAt()>=97&&lastChar.charCodeAt()<=122));
if (desc.length >= 10 || spc)
{
this.value = this.value.substring(0, desc.length-1);
} $('#spntxt').text(10 - len + ' Characters Left');
});
});
You must use the keypress event
<input type="text" onkeypress="return isValidCharacter(event)" />
and define the javascript event, the validation can do it with regular expressions
function isValidCharacter(e) {
var key;
document.all ? key = e.keyCode : key = e.which;
var pressedCharacter = String.fromCharCode(e)
var regExp = /^[a-zA-ZÁÉÍÓÚáéñíóú ]*$/;
return regExp.test(pressedCharacter); }
If the method returns true the character will be printed
For Input Length, use Html5 Max Length Property
$(function(){
$('#QI4562040').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
$('#spntxt').text(10 - input_val.length + ' Characters Left');
});
});
<input type='text' name='' id='QI4562040' maxlength='10'/>
<div id='spntxt'></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

Count textarea characters

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

Count and display number of characters in a textbox using Javascript

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

Limit number of lines in textarea and Display line count using jQuery

Using jQuery I would like to:
Limit the number of lines a user can enter in a textarea to a set number
Have a line counter appear that updates number of lines as lines are entered
Return key or \n would count as line
$(document).ready(function(){
$('#countMe').keydown(function(event) {
// If number of lines is > X (specified by me) return false
// Count number of lines/update as user enters them turn red if over limit.
});
});
<form class="lineCount">
<textarea id="countMe" cols="30" rows="5"></textarea><br>
<input type="submit" value="Test Me">
</form>
<div class="theCount">Lines used = X (updates as lines entered)<div>
For this example lets say limit the number of lines allowed to 10.
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
fiddle:
http://jsfiddle.net/XNCkH/17/
Here is little improved code. In previous example you could paste text with more lines that you want.
HTML
<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>
JS
jQuery('document').on('keyup change', 'textarea', function(e){
var maxLines = jQuery(this).attr('data-max');
newLines = $(this).val().split("\n").length;
console.log($(this).val().split("\n"));
if(newLines >= maxLines) {
lines = $(this).val().split("\n").slice(0, maxLines);
var newValue = lines.join("\n");
$(this).val(newValue);
$("#linesUsed").html(newLines);
return false;
}
});
For React functional component that sets new value into state and forwards it also to props:
const { onTextChanged, numberOfLines, maxLength } = props;
const textAreaOnChange = useCallback((newValue) => {
let text = newValue;
if (maxLength && text.length > maxLength) return
if (numberOfLines) text = text.split('\n').slice(0, numberOfLines ?? undefined)
setTextAreaValue(text); onTextChanged(text)
}, [numberOfLines, maxLength])
A much ugly , but somehow working example
specify rows of textarea
<textarea rows="3"></textarea>
and then
in js
$("textarea").on('keydown keypress keyup',function(e){
if(e.keyCode == 8 || e.keyCode == 46){
return true;
}
var maxRowCount = $(this).attr("rows") || 2;
var lineCount = $(this).val().split('\n').length;
if(e.keyCode == 13){
if(lineCount == maxRowCount){
return false;
}
}
var jsElement = $(this)[0];
if(jsElement.clientHeight < jsElement.scrollHeight){
var text = $(this).val();
text= text.slice(0, -1);
$(this).val(text);
return false;
}
});
For the React fans out there, and possibly inspiration for a vanilla JS event handler:
onChange={({ target: { value } }) => {
const returnChar = /\n/gi
const a = value.match(returnChar)
const b = title.match(returnChar)
if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
dispatch(setState('title', value))
}}
This example limits a textarea to 2 lines or 80 characters total.
It prevents updating the state with a new value, preventing React from adding that value to the textarea.

Categories

Resources