Check if value is found in array - javascript

I'm trying to check if a certain number is contained within an array.
I have tried using if (value in mines) and var value = this.value; var isMine = mines.indexOf(value);
But neither of these are working as expected. Can anyone explain why?
FIDDLE
JS
var mines = []
while (mines.length < 9){
var randomnumber=Math.ceil(Math.random() * 30)
var found=false;
for(var i=0;i<mines.length;i++){
if(mines[i]==randomnumber){found=true;break}
}
if(!found)mines[mines.length]=randomnumber;
}
$(document).ready(function() {
$(".blank").click(function() {
var value = this.value;
if (value in mines) {
$(this).removeClass("blank");
$(this).addClass("bomb");
} else {
$(this).removeClass("blank");
$(this).addClass("safe");
}
});
});
HTML
<div class="background">
<table>
<tr>
<td colspan="10"><div class="title">title here</div></td>
</tr>
<tr>
<td colspan="10"><div class="info">text here</div></td>
</tr>
<tr>
<td><button class="blank" value="1"></button></td>
<td><button class="blank" value="2"></button></td>
<td><button class="blank" value="3"></button></td>
</tr>
<table>
</div>

When it's an array you should be using indexOf, but you have two major issues.
Firstly the type has to match. The array has numbers, but the value of an element is always a string.
The easy solution is to parse the value as an integer
var value = parseInt( this.value, 10 );
Secondly, indexOf returns the index, and it will return 0 for the first item in the array, and 0 is falsy, so you have to actually check for -1, which is what indexOf returns if there is no match
if (mines.indexOf(value) != -1) { ...
FIDDDLE
A little simplified you'd end up with
var mines = [];
while (mines.length < 9){
var randomnumber = Math.ceil(Math.random() * 30);
if ( mines.indexOf(randomnumber) == -1 )
mines.push(randomnumber);
}
$(document).ready(function() {
$(".blank").click(function() {
var isBomb = mines.indexOf( parseInt( this.value, 10 )) != -1;
$(this).removeClass('blank').addClass(isBomb ? 'bomb' : 'safe');
});
});
FIDDLE

var value = +this.value
convert string to integer

You can just do this:
var myArray = ["one", "two", "three", "four"];
var myString = myArray.join("***") + "***";
var mySubstring = "four";
var inArray = myString.indexOf(mySubstring + "***");
if(inArray >= 0){alert("It's in array");}

this.value returns a string. Try this. Updated fiddle
if (mines.indexOf(parseInt(value))!=-1) { //or if (parseInt(value) in mines) {
$(this).removeClass("blank");
$(this).addClass("bomb");
} else {
$(this).removeClass("blank");
$(this).addClass("safe");
}

Related

Calculation with many fields

I have 4 fields for me to do the calculation, they should add up together and give me the total sum. However, there are some problems with fields when it is empty.
The code and script is below:
<tr id="row">
<td>No. of Dependant(s)</td>
<td><input type="text" id="Dep-main" value="0"></td>
<td><input type="text" id="Dep-joint1" value="0"></td>
<td><input type="text" id="Dep-joint2" value="0"></td>
<td><input type="text" id="Dep-joint3" value="0"></td>
<td><input type="text" id="Total-dep" readonly></td>
</tr>
The script:
<script>
var main = document.getElementById("Dep-main");
var joint1 = document.getElementById("Dep-joint1");
var joint2 = document.getElementById("Dep-joint2");
var joint3 = document.getElementById("Dep-joint3");
var total = document.getElementById("Total-dep");
1
var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input"));
inputs.forEach(function (input) {
input.addEventListener("blur", function () {
// Always supply the second argument to parseInt() (the radix) so you
// dont' get non-base 10 answers.
if (main.value.length === 0) {
total.value = parseFloat(joint1.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
} else if (joint1.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
} else if (joint2.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint3.value);
} else if (joint3.value.length === 0) {
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint2.value);
}else{
total.value = parseFloat(main.value) + parseFloat(joint1.value) + parseFloat(joint2.value) + parseFloat(joint3.value);
}
});
});
</script>
However, if there is 2 or more fields are empty, the Total field will appear NaN. Is there any way for me to keep the field as empty and get the total number?
My original idea was flawed in that it would not update the final value if a field was subsequently cleared of a value. Using an object to maintain the values for any element that has received the blur event and then performing a sum calculation of the values seems to work OK.
var total = {};
/* returns numeric value of field or zero if empty etc */
function fieldvalue(id){
var field=document.getElementById( id );
return field.value!='' && field.value.length > 0 && !isNaN( parseFloat( field.value ) ) ? parseFloat( field.value ) : 0;
}
var col=document.querySelectorAll('tr#row > td > input:not([readonly])');
if( col ){
for( var n in col )if( col[ n ].nodeType==1 ){
col[n].addEventListener('blur',function(event){
total[ this.id ]=fieldvalue( this.id );
document.getElementById('Total-dep').value=Object.values(total).reduce(function(a,b){return a+b;});
}.bind( col[n] ),false);
}
}
or, more akin to the original code using Array.prototype.slice
/*
The aim here is to select all input elements that are not marked
as "readonly" as it is these that will be used for the calculations
whilst the "readonly" field is updated programmatically only.
*/
var col=document.querySelectorAll('tr#row > td > input:not([readonly])');
/*
Convert array-like object into a true array in order that we can use
Array.forEach() method which does not work for all browsers when dealing
with HTMLCollections - such as a nodelist
*/
var inputs = Array.prototype.slice.call( col );
inputs.forEach(function(e){
/*
Assign the `onblur` event handler to each of the input elements
- the callback to the event handler will update the `total` object
which is then later processed to calculate the sum of values stored.
*/
e.addEventListener('blur',function(event){
/*
Update the total object with field value
*/
total[ this.id ]=fieldvalue( this.id );
/*
Update the "readonly" field with calculated sum of values
*/
document.getElementById('Total-dep').value=Object.values( total ).reduce(function(a,b){return a+b;});
}.bind( e ),false);
});
Perhaps worth noting is the use of Object.values(obj) - it is not supported by all browsers ( IE, Opera & Safari for instance ) but there are polyfills available here and here
And, I just wrote this - not stringently tested btw
if( typeof( Object.values )!='function' ){
Object.prototype.values=function(obj){
var tmp=[];
var keys=Array.prototype.slice.call( Object.keys( obj ) );
keys.forEach(function( item ){
tmp.push( obj[item] )
});
return tmp;
};
}
i would loop the fields, and if contains something add it.
total.value = 0;
if (main.value.length === 0) {
total.value += parseFloat(main.value);
}
if (join1.value.length === 0) {
total.value += parseFloat(join1.value);
}
if (join2.value.length === 0) {
total.value += parseFloat(join2.value);
}
if (join3.value.length === 0) {
total.value += parseFloat(join3.value);
}
I did not get what you are really after. However, I believe using such checks will lead you to the solution:
var x = $("#someFloatExpectedInput").val();
var y = $("#someIntExpectedInput").val();
if (!isNaN(parseFloat(x))) {
//
}
if (!isNaN(parseInt(y))) {
//
}
You are checking null value in if else statement that why you are getting the error so you need to check separately
Just do like this
var total=0;
if (main.value.length != 0) {
total = total+parseFloat(main.value);
}
if (joint1.value.length != 0) {
total = total+parseFloat(joint1.value);
}
if (joint2.value.length != 0) {
total = total+parseFloat(joint2.value);
}
if (joint3.value.length != 0) {
total = total+parseFloat(joint3.value);
}
total.value = total
It will help you to solve our issue.

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" />

Get highest value from <td> in table by class

How can I get the highest value in a table column by class? I have tried the following:
HTML
<table>
<tr><td class="speed">1.1</td></tr>
<tr><td class="speed">3.1</td></tr>
<tr><td class="speed">5.5</td></tr>
<tr><td class="speed">2.0</td></tr>
</table>
jQuery/Javascript
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
alert(highestspeed)
}
Also, how can I get all values if > than a certain number?
this.text is undefined for the td element, you need to parse parseFloat($(this).text(), 10);
function gethighestspeeds() {
var speeds = $(".speed").map(function() {
return parseFloat($(this).text(), 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
snippet.log('high: ' + highestspeed);
var num = 2.3;
var array = $(".speed").map(function() {
var flt = parseFloat($(this).text(), 10);
return flt > num ? flt : undefined;
}).get();
snippet.log('array: ' + array)
//if you already have the speeds array
var array2 = speeds.filter(function(val) {
return num < val;
});
snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="speed">1.1</td>
</tr>
<tr>
<td class="speed">3.1</td>
</tr>
<tr>
<td class="speed">5.5</td>
</tr>
<tr>
<td class="speed">2.0</td>
</tr>
</table>
Try this........
var certainNumber=2.2; //Whatever you want to set
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10) > parseFloat(certainNumber);
}).get();
}
You have to use : $(this).text() instead of this.text in your map function:
return parseFloat($(this).text(), 10);

Javascript shows NaN in wrong form-field in IE - works in Firefox and chrome

I am trying to setup a small article chooser. While it works in Firefox and Chrome, as well as IE7, it has problems on IE8 and IE9.
In IE 8 and 9 it changes to "increase" field to "NaN" when clicked. (edit: solved by placing a letter in front of the number)
In IE9 it updates the "Warenkorb", but places "NaN" or "\/" in
the field for "Anzahl". (edit: solved by placing a letter in front of the number)
In IE8 it completely ignores the update function. (edit: is related to the innerHTML-Bug)
To me it seems that somehow I can not reach the form itself. I have already tried to use document.forms[0] and document.getElementById["bestmult"] instead, in case the delivered object is not the field inside the form, but that did not change anything.
I feel like the solution is very simple, but I just can not put my finger on it.
Here is the code:
<script>
var sumarray = new Array();
var artarray = new Array();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
value++;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
if(value > 0){
value--;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements[field].name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements[field].value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements[field].value;
artarray[exist] = form.elements[field].name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements[field].value;
artarray[counter] = form.elements[field].name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
<div id="sum">
</div>
<form id="bestmult" action="test2.html" method="post">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td rowspan="2"><input type="text" name="1_Basis" value="0" onblur="updateCosts(this, '1_Basis', 'b')" /></td>
<td><input type="button" value=" /\ " onclick="increase(this, '1_Basis', 'b')" class="button" ></td>
</tr><tr>
<td><input type="button" value=" \/ " onclick="decrease(this, '1_Basis', 'b')" class="button" ></td>
</tr>
</table>
This code is of cause not everything there is (although everything that could potentially influence the problem at hand), so don't bother with the script tags, or the incomplete form, these where just added for completion, to show how it all fits together without having to post the whole code.
edit: it seems that IE8 and 9 have a problem with the way I named by textfields. I could resolve most of the problem by simply putting a z at the start which I can later simply strip to regain to proper text. Now it is just IE8 that does not seem to like innerHTML. I did find a lot on this on the Internet, yet nothing that really works.
Check my modifications in your script code
<script>
var sumarray = new Array();
var artarray = new String();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form1 = obj.form;
//alert(obj.form1.elements[0].value);
var value = parseInt(form1.elements(field).value, 10);
value++;
form1.elements(field).value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements(field).value, 10);
if(value > 0){
value--;
form.elements(field).value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements(field).name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements(field).value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements(field).value;
artarray[exist] = form.elements(field).name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements(field).value;
artarray[counter] = form.elements(field).name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
For ie8 indexOf() method for Array will give error. Check this
I think the problem is related to passing "this" to the function. It seems to be passing the button.
Try replacing
var form = obj.form;
with
var form=document.forms[0]
and ignore the reference to "obj"
Ok, so here is the solution packed together into one answer:
I was facing two problems:
the first one was, that an attribute name in XML can not start with a Number. I solved this by simply adding a letter in front, which i could delete for the String lateron using the replace-function.
The second problem was that the IE8 does not have the Array function indexOf(). Thank you 555k for your help here, you gave me the final piece to the puzzle. I wrote a small workaround, that suits my situation:
var exist = -1;
var needle = form.elements[field].name;
for (var i=0;i<counter;i++){
if (artarray[i].indexOf(needle) != -1){
exist = i;
}
}
This does exactly what I want, so it works for my problem. It is, of cause, not a solution to the problem of a nonexistant "indexOf()" for an aged browser, but maybe someone can use this.

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