I'm building a database of people on a WordPress website using this plugin.
I want to limit the number of characters the user can enter in certain fields (textarea and input type="text") in the signup form. Since I'm using a plugin, I can't edit the HTML of the page, so I can't just use the maxlength attribute.
How can I limit the number of characters the user can enter - and preferably also show a remaining characters count - without access to HTML? Can you tell me which files to edit, what code to use and where to put it?
You could use jQuery to set the max length as well as append: a remaining character count
$("input").each(function() {
var $this = $(this);
var maxLength = 50;
$this.attr('maxlength', maxLength);
var el = $("<span class=\"character-count\">" + maxLength + "</span>");
el.insertAfter($this);
$this.bind('keyup', function() {
var cc = $this.val().length;
el.text(maxLength - cc);
});
});
http://jsfiddle.net/0vk3c245/
You would just need to specify which input you want to apply the function to by altering "input" on the first line as well as changing the maxLength variable based on your max characters allowed for each. You could modify this function to take in parameters for multiple fields as well.
Here is a modified version that lets you apply this to multiple inputs:
http://jsfiddle.net/0vk3c245/1/
This is really easy to do with MagJS.
Here is a full working example:
HTML :
<div id="limit">
<h2>Characters left: <length/></h2>
<input>
<textarea></textarea>
</div>
JS:
var demo = {}
demo.view = function(state, props) {
state.textarea = state.input = {
_oninput: function() {
state.length = props.limit - this.value.length;
if (this.value.length > props.limit) {
alert('max length reached:' + props.limit)
this.value = this.value.substr(0, props.limit)
}
}
}
}
var props = {
limit: 10,
}
mag.module("limit", demo, props)
Here is link to working example: http://jsbin.com/sabefizuxi/edit?html,js,output
Hope that helps!
Related
I am having trouble creating a code in javascript to limit characters in an input box and trim whitespace. I am asked to use document.getElementById(, onkeyup event handler, and String.split().
I could only do this:
<script>
TextareaElement(document.getElementById("myWordsToCount"));
myTextareaElement.onkeyup = function(){
var maxlimit = 20;
var counter = maxlimit - information.value.split(/^\s+|\s+$/gm,'').length;
}
</script>
I am so new to javascript and I am thinking it might not be my zone. Anyways, I would deeply appreciate any help I could get.
Thanks
For limiting length you should use maxlenght like
input type="text" maxlength="20"
And for trim
var a =document.getElemenyById("YourId").value;
var str=a.trim();
This could be done with Jquery instead of typical JavaScript.
You could do it like :
//Now Assuming your text area has an id of "#text"
var text = document.getElementById('#text').val();
var trim = $.trim(text);
var characters = 100; //you could change the number of characters you want
$("#counter").append("You have <strong>"+ characters+"</strong> characters remaining");
$("#text").keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
var remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
You could also turn the above code into a function so that you could call this every time the user enter some text in the textbox.
I'm using Igor Escobar's jQuery mask plugin (https://github.com/igorescobar/jQuery-Mask-Plugin) and I'm trying to add a suffix to a mask to show a % sign at the end of the input value.
The application I'm building is for Brazilian users, then I have to use this number format: 000.000,00. Where , (comma) is the decimal separator and . (dot) is the thousand separator.
I wrote the following code to apply the mask, not yet appending the % sign at the end of it.
$('.mask-decimal').each(function () {
var $self = $(this);
var precision = parseInt($self.data('precision'), 10) || 2;
var mask = '#.##0,' + (new Array(precision + 1).join('0'));
$self.mask(mask, {
reverse : true,
maxlength : false
});
$self.on('keyup', function () {
var val = this.value;
if (val) {
if (val.length <= precision) {
while (val.length < precision) {
val = '0' + val;
}
val = '0,' + val;
} else {
var parts = val.split(',');
parts[0] = parts[0].replace(/^0+/, '');
if (parts[0].length === 0) {
parts[0] = '0';
}
val = parts.join(',');
}
this.value = val;
}
});
});
This mask works perfectly.
What I tried to do was add the percent symbol at the end of the mask, then remove it just in the beginning of my keyup handler, and finally append it again before return the value. I basically changed these lines:
var mask = '#.##0,' + (new Array(precision + 1).join('0')) + '%';
var val = this.value.replace('%', '');
this.value = val + '%';
After change that, I can input a value in the field, but I can't clear/change it using backspace. If I'm fast enough I can select the entire content and delete it, but it's an awful solution for regular users. It happens this way because the cursor stays always at the end of the input and the keyup event is triggered very quickly.
With that in mind, there is a way to move the cursor to a specific position inside the input? Does somebody can see another way to change my function so the user can use the backspace to clear the input contents?
If this is for an input field and the % sign is just for decoration, you could position a span containing the symbol above the input. Because it's purely a display item, right? Or you could have the sign after the input.
There's absolutely no need to have it in the input if the user's not supposed to be able to edit it. It's counterintuitive both for the user and for your logic.
Here I put the sign inside a label just so that clicking it will activate the input field.
label, input {
font-size:18px;
font-family:sans-serif;
}
label {
margin-left:-24px;
}
input {
text-align:right;
padding-right:24px;
}
<input type="text" id="number" value="123">
<label for="number">%</label>
I have 7 input textboxes.Based on the input enter i need to disable them accordingly.For eg if i enter input as 4 out the first four text boxes should be diabled accordingly(input is restricted to less than 7),and this is to be done using Jquery
This is a simple example on how to do that:
$("input").on("change", function()
{
$("input:lt(" + $(this).data("index") + ")").prop("disabled", "disabled");
});
Fiddle.
Using data attributes I set the index of each element(you can use index() in some cases, but it is more complex). So, when any element is changed I get all inputs with index less than the changed one (input:lt(index)) and disable it setting its property disabled.
I hope it is clear.
for (i = 0; i < contract; i++)
{
$('#tblTest').find('tbody').find('tr').find('.Year')[i].disabled = false;
var samtes = $('#tblTest').find('tbody').find('tr').find('.Year')[0].disabled = false;
}
I need to set the maximum number of characters allowed in an input element. Is using the maxlength attribute enough or do I need some further PHP or JavaScript validation?
This is what I have so far:
<input type="text" name="field-1" maxlength="20" />
For client-side: yes, as specification says:
When the type attribute has the value "text" or "password", this attribute specifies the maximum number of characters the user may enter.
Although, as #RobG mentioned, you have to validate data on server-side (e.g. PHP).
HTML input maxlength can be easily bypassed e.g with JavaScript.
Consider the following fiddle, that shows the problem: http://jsfiddle.net/2YUca/
In internet explorer 9 > maxlenght does not work for <textarea> fields. To get this to work you'll need to add some JS This example uses jQuery, but you could do it just as easily with standard JS
$(document).ready(function () {
$('textarea').on('keyup', function () {
// Store the maxlength and value of the field.
if (!maxlength) {
var maxlength = $(this).attr('maxlength');
}
var val = $(this).val();
var vallength = val.length;
// alert
if (vallength >= maxlength) {
alert('Please limit your response to ' + maxlength + ' characters');
$(this).blur();
}
// Trim the field if it has content over the maxlength.
if (vallength > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
delete maxlength;
});
});
Using php you can use the strlen() functio
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;}