Function with if else statement - javascript - javascript

Could anyone please tell me what I'm doing wron here?
I'm sort of new to Javascript and I can't get this function to work the way i want it..
Basically if i type in ABCJ in the number1 field , i want to display 123X in the ansarea
<!DOCTYPE html>
<html>
<body>
<script>
function convert(number1)
{
for(var i=0;i<number1.length();i++)
{
if(number1[i]=='A')
{
document.getElementById("ansarea").innerHTML="1";
}
else if(number1[i]=='B')
{
document.getElementById("ansarea").innerHTML="2";
}
else if(number1[i]=='C')
{
document.getElementById("ansarea").innerHTML="3";
}
else if(number1[i]=='D')
{
document.getElementById("ansarea").innerHTML="4";
}
else if(number1[i]=='E')
{
document.getElementById("ansarea").innerHTML="5";
}
else
{
document.getElementById("ansarea").innerHTML="x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1"><br></form>
<button type="button" onclick="convert("number1")">Convert</button>
<div id="ansarea"><input type="text" name = "ans"></div>
</body>
</html>

this will make you code work...
<!DOCTYPE html>
<html>
<body>
<script>
function convert() {
var valu = document.getElementById("some").value;
document.getElementById("ansarea").innerHTML = "";
for (var i = 0; i < valu.length; i++) {
if (valu[i] == 'A') {
document.getElementById("ansarea").innerHTML += "1";
} else if (valu[i] == 'B') {
document.getElementById("ansarea").innerHTML += "2";
} else if (valu[i] == 'C') {
document.getElementById("ansarea").innerHTML += "3";
} else if (valu[i] == 'D') {
document.getElementById("ansarea").innerHTML += "4";
} else if (valu[i] == 'E') {
document.getElementById("ansarea").innerHTML += "5";
} else {
document.getElementById("ansarea").innerHTML += "x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1" id="some"><br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</form>
</body>
</html>
you dont need to pass a value to convert() since you are getting the value from the input field, you dont need the other input field, since you putting the text in a div..

This is another working example:
<!DOCTYPE html>
<head>
<script>
function convert()
{
var number1 = document.getElementById('textbox_id').value;
for(var i=0;i<number1.length;i++)
{
if(number1.charAt(i)=='A')
{
document.getElementById("ansarea").innerHTML +="1";
}
else if(number1.charAt(i)=='B')
{
document.getElementById("ansarea").innerHTML +="2";
}
else if(number1.charAt(i)=='C')
{
document.getElementById("ansarea").innerHTML +="3";
}
else if(number1.charAt(i)=='D')
{
document.getElementById("ansarea").innerHTML +="4";
}
else if(number1.charAt(i)=='E')
{
document.getElementById("ansarea").innerHTML +="5";
}
else
{
document.getElementById("ansarea").innerHTML +="x";
}
}
}
</script>
</head>
<body>
Enter here : <input type="text" name="number1" id='textbox_id'>
</br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</body>
</html>
Few things to notice here:
You can take the value from inside the function convert()
You don't need the second onpening <html> tag after <!DOCTYPE html>
It's better not to skip the <head> tag
For this task specifically you don't need <form> so I've removed it, but you can add it if you plan to submit to some other method or something...

First, welcome to javascript ! Because you are starting, a good rule of thumb to start is to find your way around repetitions.
Here's another example on how you can execute exactly the same thing as in the other answers using a map:
// let's map all the characters you need against some digits
// this will make it super easy to add, remove or swap things around.
var map = { A: '1', B: '2', C: '3', D: '4', E: 5 };
// for example, map['A'] will now have the value of '1'
// we can store the output element once for good,
// so you don't have to look it up over and over again.
var outputElement = document.getElementById('ansarea');
function convert( inputString ) {
// the result variable will temporary store the result, so let's start empty
var result = "";
for ( var i = 0; i < inputString.length; i ++ ) {
// grab the current character so we don't have to look it up twice
var char = inputString[i];
if ( typeof map[char] !== 'undefined' ) {
// cool, the character existed within the map.
// We can append its value to the result:
result += map[char];
} else {
// ... if not add 'x'
result += 'x';
}
}
// and finally, populate the HTML with the result
outputElement.innerHTML = result;
}

innerHTML - it is property containing html in element. And every time you completely rewriting it.
Try this:
document.getElementById("ansarea").innerHTML+="1";
document.getElementById("ansarea").innerHTML+="2"; // etc
By += (instead =) you will concatenate old value with new.
And you must change you function call.
Try this (i don't test it):
function convert(selector) {
var dataFromInput = document.querySelector(selector);
var dataLength = dataFromInput.length();
var ansarea = document.getElementById("ansarea");
for(var i = 0; i < dataLength; i++) {
switch (dataFromInput[i]) {
case 'A':
ansarea.innerHTML += '1';
break;
case 'B':
ansarea.innerHTML += '2';
break;
case 'C':
ansarea.innerHTML += '3';
break;
case 'D':
ansarea.innerHTML += '4';
break;
case 'E':
ansarea.innerHTML += '5';
break;
default:
ansarea.innerHTML += 'x';
}
}
}
and add id for input:
<form>Enter here : <input type="text" name="number1" id="number1"><br></form>
<button type="button" onclick="convert('#number1')">Convert</button>

Related

HTML, JS Tables will not update properly

I am new to learning these languages, and everything looks syntactically correct. The issue I'm having is that the correct button will just keep click as correct rather or not the answer is correct or not. The tables are updating, but I'm not sure where the issue is. The if-else statement looks to be okay (I know I don't need the else if in there). If anyone could help me figure out what is wrong I would appreciate it.
window.onload = function() {
equations();
};
window.onload = equations;
var sum;
var correct = 0,
incorrect = 0;
function equations() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ['+', '-', '÷', 'x'];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length)
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return (sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight() {
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl = document.getElementById('incorrectCount');
sum = equations();
if (userInput = sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput = '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<body>
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function() {
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="button" id="submit" value="Enter" onclick="confirmIfRight()" onclick="document.getElementById('userInput').value = '' " />
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
</body>
The main reason your code wasn't working is because you aren't using the equality operator (==), you are using the assignment operator (=) in your if..else statements. Fixing that alone should resolve the main problem in your question.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
However, this presents another problem in your code immediately: you're comparing sum immediately after reassigning it in confirmIfRight(). A new equation will have been generated prior to the comparison. This means the value in sum will most likely not be correct considering the original equation presented and the answer given.
To resolve this, remove the sum = equations(); line just before the if..else statements:
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Additionally, I do agree that you can remove the else if section and this should capture all cases where the answer does not equal the expected result.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Testing a few times showed that this is all you need to have your code working. Run the code snippet below as an example:
window.onload = equations;
var sum;
var correct=0, incorrect=0;
function equations(){
var a,b,sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a+b , a-b ,a /b ,a *b ];
signs = ['+', '-','÷','x'];
//assign random opperation
let randoArr = Math.floor(Math.random()*solve.length)
sum=solve[randoArr];
showSign=signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return(sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight(){
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl= document.getElementById('incorrectCount');
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function(){
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput"/>
<input type="button" id ="submit" value="Enter"onclick="confirmIfRight()" onclick=
"document.getElementById('userInput').value = '' "/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
There were a few mistakes that you did. The main issue was that you were generating a new equation and sum value every time you call equations function.
So I've saved the value in a new hidden input that is visually hidden from the user. And then compare it to the user input value. There is a plus sign in front of some methods and it is to convert the value to a number. Also, I allowed myself to make a few code naming changes so the code can feel better. Also, you can remove the return statement in the equation method since it has no reason to be there anymore.
let correct = 0,
incorrect = 0;
function generateEquation() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ["+", "-", "÷", "x"];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length);
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById("showMath").innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
document.getElementById("hiddenInput").value = sum;
return sum;
}
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function isCorrect() {
let userInput = +document.getElementById("userInput").value;
const correctEl = document.getElementById("correctCount");
const incorrectEl = document.getElementById("incorrectCount");
if (userInput === +document.getElementById("hiddenInput").value) {
correct++;
correctEl.textContent = correct;
generateEquation();
} else if (userInput == "") {
incorrect++;
incorrect.textContent = incorrect;
generateEquation();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
generateEquation();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById("userInput").value = "";
}
generateEquation();
<!DOCTYPE html>
<html lang="eng">
<head>
<link rel="stylesheet" href="fastmath_style.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial scale = 1" ; />
<title>Fast Math</title>
</head>
<body>
<h1>Welcome to Fast Math!</h1>
<p>A website for solving simple math problems.</p>
<!-- Math Stuff-->
<div id="showMath"></div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="hidden" id="hiddenInput" />
<input
type="button"
id="submit"
value="Enter"
onclick="isCorrect()"
onclick="document.getElementById('userInput').value = '' "
/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount">0</td>
<td id="incorrectCount">0</td>
</tr>
</table>
<script src="./app.js"></script>
</body>
</html>

JS or jQuery to compare two texts character by character

It should compare the texts and update it. I am using onkeyup for each time text is updated.
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
var pass = $('#coltext').text();
var length = $("#color").val().length;
for (int i = 0; i < length; i++) {
if (pass[i] == password1[i]) {
$("#coltext").css("color", "green"); //make only correct character green
} else {
$("#coltext").css("color", "red");
}
}
}
<input id="color" type="text" />
<p id="coltext">This</p>
So what I want to do is whenever I type the "This" written should update character by character, green for correct and red for wrong. You can say like what typing tutor does.
You have to break the password into spans in order to style them seperately, then to compare then use $("#coltext span").eq(i).text() instead of pass[i];
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
// put each of your password chars in a span
var pass = "<span>"+$('#coltext').text().split("").join("</span><span>")+"</span>";
$('#coltext').html(pass);
var length = $("#color").val().length;
for (var i = 0; i < length; i++) {
if ($("#coltext span").eq(i).text() == password1[i]) {
$("#coltext span").eq(i).css("color", "green"); //make only correct character green
} else {
$("#coltext span").eq(i).css("color", "red");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="color" type="text" />
<p id="coltext">This</p>
<!DOCTYPE html>
<html>
<body>
<script>
var x = "Cancelled";
var y = "Cancelled";
if(x==y)
{
alert("equal");
}
else
{
alert("not equal");
}
</script>
</body>
</html>

Getting comma separated values into input field

I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />

how to do a printer-like text field using javascript OOP

I'm doing a printer-like text field which could show the letter one by one. I could realize it just use a function and load it as simple like:
html---
<div id="myTypingText"></div>
js---
<script>
var myString = "Place your string data here, and as much as you like.";
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
But I want to do more advanced, I want to let the user to change the speed and change the text, so I wrote the following one but it went wrong, why? help me .thx.
html----
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
js----
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
this.loop = function (){
if(this.len > 0 ){
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
You need to use an anonymous function in the interval if you want the loop function to be executed in the context of the Printer object. Also you need to check the length of the array each time as the len property won't be updated when the array is shifted.
function Printer() {
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.loop = function () {
if (this.myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin() {
var test = new Printer();
setInterval(function () {
test.loop()
}, test.tempo);
}
See the working fiddle
Here's another approach. Your fundamental problem was with using the this keyword. You have to remember that when you enter another function scope, the this keyword changes. You'll notice here that I cache or save 'this' to equal that, then use that new 'that' value in the function. Plunker
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
var that = this;
this.loop = function (){
if(that.myArray.length !== 0 ){
document.getElementById("myTypingText").innerHTML += that.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
</body>
</html>

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories