Limit text area value and cut the rest - javascript

I have a textarea which users can enter some tags.
I need to limit this tags to 20 tags.
Tags could be enterer this way
maytag1,mytag2,mytag3
What i wrote is this function
function limitTags()
{
var tags = $("input[type=text][name=tags]").val()
var tag = $.trim(tags);
var selected = new Array();
/**
* replace the last ','
*/
if(tag.substring(tag.length - 1) == ",")
{
*///tag = tag.replace(tag.length - 1, '');
}
var enteredTags = tag.split(",");
if( enteredTags.length > 20 )
{
//$("input[type=text][name=tags]").val(enteredTags.join(",", enteredTags));
alert("Only 20 Tags allowed");
}
}
The alert works just fine but, after the alert box is gone. i can continiue entering tags till the alert box appears.
What i need is cut the text after the messagebox which was entered also the last ","
I hope i could ask my question clear.
Thanks

You can use the slice method to cut the array down to 20 entries before setting the value:
$("input[type=text][name=tags]").val(enteredTags.slice(0,20).join(","));
See: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice

Intercept "," pressing, and check how many entries the user inserted so far. If he's trying to insert too many entries just prevent further insertions.
$('input[type=text][name=tags]').keyup(function(e) {
if((e.keyCode == 188) && ($(this).val().split(",").length > 19)) {
alert('Only 20 Tags allowed');
}
});

Related

next button not highlighting or displaying matches

The jquery highlight that I have created works well, but for some reason when I type something in the input field and hit the next button it doesn't highlight the terms. It only displays "1 of 0 mathches". I'm not sure why it won't highlight it.
Below is my script:
<script>
$("[data-search=next]").click(function() {
if (variableCounter < totalCount) variableCounter = variableCounter + 1;
else variableCounter = 1;
$(".kwt-count").html(variableCounter + " of " + totalCount + " Matches");
});
</script>
Also when the term is in the field and I hit the enter key it highlights the verbiage, but when I hit the delete key it unmarks the content, but the full string is removed along with the highlight. I want it to remove "all" highlights on delete or backspace key, but not remove the full string from the input field. Not sure why its removing everything in the input field.
<script>
$input.keydown("input", function(e) {
if (e.keyCode === 46 || e.keyCode === 8) {
$content.unmark();
$input.val(" ").focus();
}
});
</script>
I have created a codepen of my code here: https://codepen.io/dude12go8/pen/PoYbdXd

How Can I Only Allow Text Entry at Start of Input Field, and Always Append Text

I previously had a requirement to always prepend (to put at the beginning) some static text to whatever was entered in a text input field, and to never allow that static text to be deleted. I found a solution that works really well.
Not my requirement has changed, and I need to append (to put at the end) some static text, to whatever is entered in a text box. I'd like the static text to be displayed in the text box at all times, and for any text entered to be placed before the static text. Ideally, the cursor would automatically be placed at "position zero" in the text input whenever a user clicks on the input, or tabs into it.
Here's a Fiddle that shows first the working example of the text being prepended, and then the non-working example of the appending:
https://jsfiddle.net/dsdavis/x9d36veu/25/
When one starts typing in the second example, you'll see that only the last character typed is displaying at the beginning of the box.
A slight difference between how I implemented them that is worth pointing out, is that in the working example, I use the "indexOf":
$(document).ready(function() {
$('#prepend').keyup(function(e) {
if (this.value.length < 16) {
this.value = 'Student Worker - ';
} else if (this.value.indexOf('Student Worker - ') !== 0) {
this.value = 'Student Worker - ' + String.fromCharCode(e.which);
}
});
});
and in the non-working example, I use "lastIndexOf":
$(document).ready(function() {
$('#append').keyup(function(e) {
if (this.value.length < 17) {
this.value = ' - Student Worker';
} else if (this.value.lastIndexOf(' - Student Worker') !== 17) {
this.value = String.fromCharCode(e.which) + ' - Student Worker';
}
});
});
Maybe using "lastIndexOf" is totally wrong, but it seemed like the right way to go.
Can anyone help me come up with a way to do this? To always display the static text " - Student Worker" in the text box, and to put any text that is entered before that static text?
Thank you!
Doug
another approach entirely:
$(document).ready(function() {
$('#append').on("input", function(e) {
var s = this.value.replace(" - Student Worker", "");
this.value = s + " - Student Worker";
});
});

How to count and limit the text from 2 text fields in a form?

i tried to count and limit the user inputs from two text fields. that means max char is 20, then user can enter only 20 char in both text fields.I tried like this
$(document).ready( function() {
jQuery.fn.getLength = function(){
var count = 0;
var max=$("#max").val();
this.each(function(){
count += jQuery(this).val().length;
});
var rem=max-count;
return rem;
};
var $inputs= jQuery('#left,#right');
$inputs.bind('keyup',function(){
var remain=$inputs.getLength();
jQuery('#count').html($inputs.getLength());
$("#left").keyup(function(){
if($("#left").val().length > remain){
$("#left").val($("#left").val().substr(0, remain));
}
});
$("#right").keyup(function(){
if($("#right").val().length > remain){
$("#right").val($("#right").val().substr(0, remain));
}
});
});
});
but it only works for single text box, doesn't take values from 2 fields. any help please..
All you need is this code, it detects the keypress in either #left or #right, if the count of the two is more than 20, it removes the last character typed
$("#left,#right").keyup(function () {
var charCount = $('#left').val().length + $('#right').val().length;
if (charCount > 20) {
difference = -Math.abs(charCount - 20);
$(this).val($(this).val().slice(0, difference));
}
});
Demo http://jsfiddle.net/k8nMY/
My first solution worked on keydown and used return false to stop further entry, however this had the effect of disabling backspace and other keys.
This solution, which executes on keyup waits until after the key is pressed then counts characters. If the number is over 20 it will remove the last character typed. This way, the user can still press backspace and make changes as they wish, but not go over 20 chars.
I have also modified the script further, what it does is detect ANY change, e.g. a paste of a long string. It removes the 'difference' above 20 characters.
This should be a complete solution to the problem.
DEMO: http://jsfiddle.net/EEbuJ/2/
JQuery
$('#left, #right').keyup(function(e) {
if (maxLen() <= 20)
{
// Save the value in a custom data attribute
$(this).data('val', $(this).val());
} else {
// over-ride value with saved data
$(this).val($(this).data('val'));
}
});
function maxLen() {
var x = 0;
$('#left, #right').each(function() {
x += $(this).val().length;
});
return x;
};
This will save the typed in value for your inputs to a custom data attribute, if the total number of characters in the specified inputs is no more than 20.
When the maximum number of characters is reached then we stop saving the typed in value and revert the value back to our previous save (i.e. less than the maxiumum) effectively undo-ing the value.
Well it should be easy one: http://jsfiddle.net/4DETE/1/
var textLength =$inputs.eq(0).val().length+$inputs.eq(1).val().length;
if(textLength>=20)
return false
just count length of values, if you'll have more elements to limit, use jquery.each to iterate inputs
I doubt you can do $inputs.getLength() as $inputs is an array and thus will return the arraylength: 2
You will have to add up the overall sign length in both inputs:
$('#left,#right').keydown(function(){
var leftlength = $('#left').val().length;
var rightlength = $('#right').val().length;
if(leftlength + rightlength > 20)
{
return false;
}
});
or to make it shorter
if($('#left').val().length+$('#right').val().length >20){return false;}

How to restrict the user from typing more than certain characters in a editable div or Iframe

I have an editable div and iFrame. I require that the user must not be able to type more than 100 characters per line. The user can enter infinite number of lines all having maximum 100 characters.
Also the user can go back to any line, using arrow keys and enter more text in case that line had less that 100 characters.
How to perform this?
EDIT:
This needs to be like in real time as the user types.
$('#mydivid').keypress(function(e){
if($(this).html().length > 20)
e.preventDefault();
})
Fiddle
you can check with jquery keyup event.
$('DIV ID').keyup(function(){
data = $.trim($('DIV ID')).html().length;
if(data > 100) // or add condition as per your requirement
{
}
else
{
alert('Your message')
}
});
$(document).ready(function(){
var max_length = 100;
$("#div-editable").keypress(function(){
var return_state = true;
$(this).find("div").each(function(){
if($(this).text().length >= max_length)
{
return_state = false;
//break;
}
});
return return_state;
});
});
Just change max_length to your needs.
Also you can use Trim if you want to allow spacing on start and end of the text.
You can check this on jsFiddle

TextArea with 10 lines and 35 characters per line

I have an HTML page with many elements. The page is scrollable, that means the page has a scrollbar in it. Down to the page I have a HTML textarea with a specified rows and columns attribute.
Now I want a simple JavaScript solution which will help me to validate the the following points each time user enters any character:
The number of lines in the textarea is not greater than 10
Each line has less than or equal to 35 characters
If user crosses 35 character limit for any particular line then the 36th character will be automatically start from next line only if the total line numbers does not exceed 10, else it will show an error popup message and stops there.
User should be able to modify any lines(it may be last line or any middle lines) and still should follow all the above 3 points.
I used the following to limit the amount of characters allowed in my textarea.
This not only counts the amount of characters it trims it if it gets to the end and it also writes out how many characters you have left.
I think all you need to do now is figure out how to add a new line (try something like text += "\r\n";) <- Not 100% sure on this peice.
function textCounter(txtfield, cntFld, maxlimit){
var field = document.getElementById(txtfield);
var countfield = document.getElementById(cntFld);
if (field.value.length > maxlimit) // if too long...trim it!
{
field.value = field.value.substring(0, maxlimit);
}else { // otherwise, update 'characters left' counter
countfield.innerHTML = maxlimit - field.value.length;
}
}
I have done a similar case :
MaxLenght of textarea = 1875 ;
MaxLenght of row = 75 ;
Disable Enter, because over 75's multiple, SW automatically wrap text ;
This is it, with onkeydown trigger:
function wrapTextArea(event,id,maxLineLenght){
// delete and canc
if((recuperaKeyCode(event)!=8) && (recuperaKeyCode(event)!=46)) {
var field = document.getElementById(id).value;
var nextIndex = 0;
for(var i=0; field.length>nextIndex; i++){
nextIndex=maxLineLenght*(i+1)+i;
if(field.length==nextIndex){
if(field.charAt(nextIndex)!= "\n"){
field=field.substring(0, nextIndex)+"\n"+field.substring(nextIndex, field.lenght);
}
}
}
document.getElementById(id).value = field;
}
}
This is how I disabled enter key, where key = 13 :
function disableKey(event,key){
if(recuperaKeyCode(event)==key){
event.preventDefault();
}
}

Categories