Trying to limit the max characters in a textarea - javascript

I'm trying to limit the max characters in a textarea, using JS, i leave here my HTML & JS code:
HTML-->
<form id="formu" action="ok.html" method="post" enctype="multipart/form-data">
<p>
<label for="observaciones">Observaciones:</label>
<textarea id="observaciones" cols="30" rows="5"></textarea>
</p>
</form>
JS-->
window.onload=function(){
document.getElementById("observaciones").addEventListener('keypress',function(){maxlong(document.getElementById("observaciones")),150},false);
}
function maxlong(obj,maxlength){
return(obj.value.length<=maxlength);
}

your event handler doesn't actually do anything. You need to prevent the default beahviour of the event (with the preventDefault method on the event object).

You can do this by html :
<textarea maxlength="50"> </textarea>

try this:
function limiter() {
var area = document.getElementById("content_txt");
var message = document.getElementById("message");
var maxLength = 160;
var checkLength = function () {
if (area.value.length <= maxLength) {
message.innerHTML = (maxLength - area.value.length) + " characters remainging";
}
}
setInterval(checkLength, 300);
}
and this is the textarea
<textarea style="resize:none; margin-bottom: 0px;" id="content_txt"
name="TextArea1" runat="server"
maxlength="160" onkeyup="return limiter();" ></textarea>

<script>
function maxLength(obj){
if(obj.value.length <=150){
return true;
}else{
return false;
}
}
</script>
<textarea onkeypress="return maxLength(this);"></textarea>

This is basic to set maxlength:
<textarea maxlength="50">
Enter text here...
</textarea>

Solved doing this:
function maxlong(elEvento){
var evento=elEvento||window.event;
var obser=document.getElementById("observaciones").value;
if(obser.length>=15){
evento.preventDefault();
}
}
And also i had an extra "{" that made the program not working well...

Related

TextCounter & Trigger innerHTML in two separate input areas

I just started to learn Javascript. I have two questions regarding TextCounter & Trigger innerHTML.
My code below, how to separately trigger innerHTML for two inputs?
Why the alert info which is "over!!" still shows while deleting the number of words in the textarea?
Can someone please help? Much appreciated!
HTML
<html>
<head>
</head>
<body>
<form>
<textarea name="line01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.01,this.form.countDisplay01,10);"
onKeyDown="textCounter(this.form.01,this.form.countDisplay01,10);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" width: 25px"
value="10">characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="line02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.02,this.form.countDisplay02,8);"
onKeyDown="textCounter(this.form.02,this.form.countDisplay02,8);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" width: 25px"
value="8">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
Javascript
<script>
function textCounter(textField, showCountField, maxAmount) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
} else {
document.getElementById("go1").innerHTML = "<span
style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span
style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
</script>
Try with the following code
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Text Counter</title>
</head>
<body>
<form>
<textarea name="01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['01'],this.form.countDisplay01,10,1);"
onKeyDown="textCounter(this.form['01'],this.form.countDisplay01,10,1);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" style="width: 25px;" value="28"> characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['02'],this.form.countDisplay02,8,2);"
onKeyDown="textCounter(this.form['02'],this.form.countDisplay02,8,2);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" style="width: 25px" value="15">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
SCRIPT
<script>
function textCounter(textField, showCountField, maxAmount,id) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById('go'+id).innerHTML = '';
} else {
document.getElementById('go'+id).innerHTML = '<span style="color:red">Over!!</span>';
textField.value = textField.value.substring(0,maxAmount);
}
}
</script>
As you have used a name that starts with number, it's not a valid variable. You should access it through dictionary lookup:
textCounter(this.form['01'],this.form.countDisplay01,10);
For the alert text, you should reset the innerHTML in the first if clause:
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById("go1").innerHTML = "";
document.getElementById("go2").innerHTML = "";
} else {
document.getElementById("go1").innerHTML = "<span style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
This will remove the alert text, on the next keypress. If you want to remove the text immediately, you have two options:
Forget about showing an error.
Show the error for about a fraction of second and then remove it. Using something like a setTimeout. But you should remember, the window won't redraw before returning from your function. So, setting the alert text first, and then removing it at the end of your function, will be the same as doing option 1.

iFrame break on enter key

I have an iFrame to create a message. However, when I press enter while typing in the iFrame, it creates another div, however, I want it to create a <br/>. I tried using the execCommand insertBrOnReturn, but I did not get it to work. Any idea's? Thanks in advance!
The JSFiddle in stackoverflow doesn't really work, but I have an existing one at "Craz1k0ek/d869w67b/" after the default jsfiddle.net
function iFrameOn() {
richTextField.document.designMode = 'On';
richTextField.document.body.style.fontFamily = 'Open Sans,Helvetica Neue,Helvetica,Arial,sans-serif';
}
function iBold() {
richTextField.document.execCommand('bold', false, null);
}
function iUnderline() {
richTextField.document.execCommand('underline', false, null);
}
function iItalic() {
richTextField.document.execCommand('italic', false, null);
}
function submit_form() {
var theForm = document.getElementById("myForm");
theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
<body onload="iFrameOn()">
<form action="" name="myForm" id="myForm" method="post">
<p>
Title
<input name="title" id="title" type="text" size="80" maxlength="80">
</p>
<div id="wysiwyg_cp" style="padding:8px; width:700px;">
<input type="button" onClick="iBold()" value="B">
<input type="button" onClick="iUnderline()" value="U">
<input type="button" onClick="iItalic()" value="I">
</div>
<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
<iframe name="richTextField" id="richTextField" style="border:#000 1px solid; width:700px; height:300px;"></iframe>
<input name="myBtn" type="button" value="Submit Data" onClick="javascript:submit_form();">
</form>
</body>
I changed the submit_form function as follows:
function submit_form() {
remove_divs();
var theForm = document.getElementById("myForm");
theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
And then I added the remove_divs function which is as follows:
function remove_divs() {
var frameHTML = window.frames['richTextField'].document.body.innerHTML;
frameHTML = frameHTML
.replace(/<div><br><\/div>/g, '')
.replace(/<div>/g, '<p>')
.replace(/<\/div>/g, '</p>');
$(window.frames['richTextField'].document.body).html(frameHTML);
}
It replaces all the <div><br></div> elements with nothing and then it replaces all the <div> elements with <p> and all the </div> elements with </p>. This formats the text in the field exactly as I want.
Then I had an issue with setting the DesignMode = 'On'; I solved that by placing extra code in the javascript file as follows:
window.onload = function() {
window.frames['richTextField'].document.designMode = "On";
}
I also got some minor warnings on how I gained access to the richTextField, so I replaced all the richTextField.document.execCommand elements for window.frames['richTextField'].document.execCommand.
I hope this helps!

Jquery/Form - check input field is at least 5 characters long - and also doesn't match certain words

I have a very simple form. Full Name/Email. What I want to do is check with jquery to make sure that they entered AT LEAST 5 characters in the name field. And if they did not, then I don't want the form to be submitted, instead I want to print some HTML below the form showing a warning/error message. How can I accomplish this?
Also Can I add words manually to the script to make sure they were not entered in the name field? And if they were to make sure it prints errors again... For example, if they entered the word "bobby" or "stephanie" I don't want the form to be submitted if those EXACT words are entered. It is only like 5 or 6 words I want blocked, so I can enter them manually no problem in the script without bloating anything.
Thank you so much in advance.
Here is my HTML
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1">
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email">
</div>
And this is the added HTML I want printed if the jquery check is false
<div id="error">
<span class="error_message">Please enter your full name</span>
</div>
Let's assume your form has an id of myForm.
var words = ["bobby", "stephanie"];
jQuery('#myForm').on('submit', function(evt) {
var form = $(this);
var full_name = form.find('#full_name');
var name_length = full_name.val().length;
if( name_length < 5 ) {
jQuery('#error').show();
evt.preventDefault();
}
if( jQuery.inArray(full_name.val(), words) ) {
evt.preventDefault();
}
});
Here is my answer: there are two if statements that we can construct:
Test if length of input exceeds 5 characters, and
Test if the input matches a list of banned words (stored in an array for convenience and verbosity)
It is a little complicated with the second conditional statement, since we want an exact match (therefore, using 'bobby' will raise a flag, but not 'bobby123'. This involves the use of word boundaries, \b.
You can view the code in action in this fiddle: http://jsfiddle.net/teddyrised/kmMcC/
$('form').submit(function(e) {
var errorFlag = 0,
bannedWords = [
'bobby',
'stephanie'
],
bannedObj = new RegExp('\\b'+bannedWords.join('|')+'\\b', 'i');
if($('#full_name').val().length <= 5) {
errorFlag = 1;
}
if(bannedObj.test($('#full_name').val())) {
errorFlag = 1;
}
// Act on error flag, prevent form submission when one or more error flags are raised
if(errorFlag) e.preventDefault();
});
Assuming you put this all in a form element, and add an input type='submit' element to it, I would suggest setting the form's onsubmit attribute to "return Validate();", and add the below validation function.
First you'll want to hide the message on ready using: $('error').hide();
function Validate(){
var minLength = 5;
var blockedNames = ["bobby","stephanie"];
var fName = $('#full_name').val();
if(fName.length < minLength){
$('#error').show();
$('#full_name').focus();
return false;
}
for(var i = 0;i < blockedNames.length;i++){
if(fName == blockedNames[i]){
$('#error').show();
$('#full_name').focus();
return false;
}
}
return true;
}
JSFIDDLE DEMO: http://jsfiddle.net/softvar/hv6yB/2/
UPDATE:
HTML
<form onsubmit="return check()">
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1" />
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email" />
</div>
<input type="submit" value="Submit"/>
</form>
<div id="error" >
<span class="error_message">Please enter your full name</span>
</div>
CSS
#error {
color:red;
display: none;
border: 1px solid #D9534F;
background: #FDF7F7;
width: 80%;
height: 25px;
padding: 5px;
}
JS
function check() {
var bannedWords = ['bobby','stephen'];
var name= $('#full_name').val();
if(name){
if(name.length>5){
for(var i=0;i<bannedWords.length;i++) {
if(bannedWords[i] ==name){
$('#error').text('Its a banned word');
$('#error').css('display','inline-block');
return false;
}
}
alert('form is going to be submitted');
return true;
}
else{
$('#error').text('Name is shorter');
$('#error').css('display','inline-block');
return false;
}
}
$('#error').text('Name cant be blank');
$('#error').css('display','inline-block');
return false;
}

I cant enable the button again in javascript

I am trying to control the password input. And when it is less than 6 characters , I dissable tthe button and dispay an error mesage...But my problem is that when the password is greater than 6 characters the mesage appears again and the button is still disablet...What can I do?
the function is below..Please help me
function passcheck() {
var pass = document.getElementById('password1');
var sb = document.getElementById('submit');
if (pass.value.length < 6) {
document.getElementById('error').style.display = 'block';
sb.disabled = true;
} else {
document.getElementById('error').style.display = 'none';
sb.disabled = false;
}
}
HTML:
<input type="password" name="password1" id="password1" class="textinput" style="margin-left: 15%;margin-top: -2.5%;width: 30%" onchange="passcheck()">
<br>
<input type="button" value="Submit" id="submit" onclick="location.href='userlogin.html'" class="button" style=" margin-top: 4%;width: 15%" >
<br>
Disabled is a property, not an attribute.
Use:
.removeAttribute("disabled");
Use onkeyup instead of onchange for calling passcheck().

How to get a script to activate on modal load?

I have a modal that is prepopulated with some text for the user to edit, with a limit of 500 characters. I wanted to include a 'remaining character' notification. I have it working for the onKeyUp, but I want it to initialize with how many characters are left (right now the span is empty until the user hits a key). Neither of the onLoad functions are working (maybe onLoad is wrong? Fairly new here). Any help is appreciated!
<div id="tooltip-modal" style="display:none">
<script language = "Javascript">
maxLength = 500;
var container = $("#tooltip_body");
function taCount(tooltipBody,Cnt) {
objCnt = createObject(Cnt);
objVal = tooltipBody.value;
if (objCnt) {
objCnt.innerText=maxLength-objVal.length;
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
onLoad="alert('Loaded')";
onLoad="return taCount(container,'myCounter')";
</script>
<body>
<form method="post" action="#" id="update-tooltip">
<h2>Edit the description of this item:</h2>
<input type="hidden" name="tooltip_id" id="tooltip_id">
<textarea onKeyUp="return taCount(this,'myCounter')" name="tooltip_body" id="tooltip_body" class="input" rows=7 wrap="physical" cols=40></textarea>
<br><br>
You have <strong><span id="myCounter" ></span></strong> characters remaining for your description...</h3><br>
<button type="submit" value="Update" id="update" >Update</button>
</form>
</body>
</div>
Pretty sure that onload has to be tied to an element on the page, such as the body tag.
http://www.w3schools.com/jsref/event_onload.asp

Categories

Resources