Textarea validation by javascript - javascript

there are 2 kinds radio buttons.
If check sms button, then textarea's maxlength sets 90 bytes
If check lms button, then testarea's maxlength sets 2000 bytes
and We can check how many I put texts on the textarea at 'totalWordLimit'
but have problems
If I put many texts by copy & paste, textarea become disabled
and also when I change radio buttons, counting number doesn't initialize.
What I need to fix in this code?
<script type="text/javascript">
var setTotalNumberOfWordCounter = "90";
function displayWordCounter(){
var getTextValue = document.smsForm.msg.value; // Get input textarea value
var getTextLength = getTextValue.length; // Get length of input textarea value
var one_char = "";
var rbyte = 0;
var rlen = 0;
for(var i=0; i<getTextLength; i++){
one_char = getTextValue.charAt(i);
if(escape(one_char).length > 4){
rbyte += 2; // special language(2Bytes)
}else{
rbyte++; // 1Byte
}
if(rbyte <= setTotalNumberOfWordCounter){
rlen = i+1; //return text count
}
}
if(rbyte > setTotalNumberOfWordCounter){ //compare this length with total count
getTextValue = getTextValue.substring(0,setTotalNumberOfWordCounter);
document.smsForm.msg.value =getTextValue;
return false;
}
document.smsForm.totalWordLimit.value = (setTotalNumberOfWordCounter-rbyte);
var tt = document.getElementById("Textarea");
if(document.smsForm.totalWordLimit.value === "0"){
tt.value = tt.value.substring(0, tt.value.length-1);
}
}
</script>
<script type="text/javascript">
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
setTotalNumberOfWordCounter = "90";
}else if(document.getElementById('lms').checked) {
setTotalNumberOfWordCounter = "2000";
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="sms" id="sms" onclick="ShowHide()" value="ss" checked>SMS
<input type="radio" name="lms" id="lms" onclick="ShowHide()" value="ll"> LMS
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" ></textarea>
<script type="text/javascript">
document.write("<div class='total_count'>total remaining Charatctor: <input type='text' class='show_count' name='totalWordLimit' size=4 readonly value="+setTotalNumberOfWordCounter+"></div>");
</script>

Try this one
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
Textarea.setAttribute("maxlength", "90");
}else if(document.getElementById('lms').checked) {
Textarea.setAttribute("maxlength", "2000");
}
}
and try onpaste function in the textarea element
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" onpaste="return displayWordCounter();"></textarea>

Related

Get number of characters selected from a text inside textarea or input text [duplicate]

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

Trying to print out a input text the number of times the user wrote in the secound input using a while loop

I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}

Remove line with specific word from text area using javascript

I am trying to remove line with specific word using javascript from textarea.
Here is example
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
If the user enters the value in input field the line which contains it should be removed. Suppose user enters CxPh1tgiK2g or xOYPv7CxMVk the line which contains those ids should be removed
Try
$("#remove").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
lines = lines.filter(function(val) {
if (val.match(text)) return false
else return true
})
$('#textarea').text(lines.join('\n'))
})
$("#replace").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
var n = Math.floor(Math.random()*lines.length)
lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
$('#textarea').text(lines.join('\n'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>
<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
As solution to remove line with inclusion
var value = test.value.split(/\n/g).filter(function(val)
{
return val !== "";
});
console.log(value);
setTimeout(function()
{
var index = value.findIndex(function(val)
{
return val.includes('kKC7-ACrs1w');
});
if (index !== -1)
{
value.splice(index, 1);
test.value = value.join("\n");
}
}, 2000);
.text {
width: 100%;
resize: none;
height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
You can do something like this:
var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);
}
}
ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>

How to check value in input using loop for with onchange using javascript?

How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>

Disable/Enable Submit Button until all forms have been filled

I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>

Categories