Javascript error box - javascript

Hi guys I have this script here, which counts the characters and lines, now currently though it still allows lines and characters to go into minus, but I would like it to also put up a warning box so it stops the user from being able to put in more text, could you help me out?
javascript:
function textCounter(theField,theCharCounter,theLineCounter,maxChars,maxLines,maxPerLine) {
var strTemp = "";
var strLineCounter = 0;
var strCharCounter = 0;
for (var i = 0; i < theField.value.length; i++)
{
var strChar = theField.value.substring(i, i + 1);
if (strChar == '\n')
{
strTemp += strChar;
strCharCounter = 1;
strLineCounter += 1;
}
else if (strCharCounter == maxPerLine)
{
strTemp += '\n' + strChar;
strCharCounter = 1;
strLineCounter += 1;
}
else
{
strTemp += strChar;
strCharCounter ++;
}
}
theCharCounter.value = maxChars - strTemp.length;
theLineCounter.value = maxLines - strLineCounter;
}
and used in code:
<textarea name="comment" cols="50" rows="10" wrap="VIRTUAL" onKeyUp="textCounter(theForm.comment,theForm.remChars,remLines,900,30,50);"></textarea>
<br><input name=remChars type=text value="900" size=3 maxlength=3 readonly> characters left
<br><input name=remLines type=text value="30" size=3 maxlength=3 readonly> lines left<br>
Report to moder

1 - Add a check to the end of the function:
var check = strTemp.length <= maxChars && strLineCounter <= maxLines;
if (!check) alert("Error message here!");
2 - Trim the text of the field, so it contains only the needed chars:
theField.value = theField.value.sbustring(0, maxChars - 1);
3 - Add a return to the end of the function:
return check ;
4 - And change the event binding to:
onKeyUp="return textCounter(theForm.comment,theForm...

Related

While Loop Input Issue

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!
You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

Display times table up to 12 based on the users input

it seems to think ttinput is a string when I console.log the variable it says "". All else seems to working I just can't figure out how to have ttinput as a number.
document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;
function ttcalc(){
var display = "";
for(var i = 1; i <= 12; i++){
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
}
this is my html
<form>
<h1>Enter what times table you wish to see</h1>
<input type="number" id="table"><br>
</form>
<button id="enter">Show Times Table</button>
</div>
The problem is that the value of
var ttinput = document.getElementById("table").value;
is read on page load (while the input field is empty). If you move that line of code inside your function it will read the value of the input field after the button is clicked.
If you want to be sure the value entered is a number you can use the parseInt() function and then check if the result is a number with the isNaN() function like this:
var ttinput = parseInt(document.getElementById("table").value);
and then use isNaN():
if( !isNaN(ttinput) ) {
// ttinput is a number
} else {
// ttinput is not a number
}
More here: parseInt and isNaN.
Check example below:
document.getElementById("enter").addEventListener("click", ttcalc)
function ttcalc() {
var ttinput = parseInt(document.getElementById("table").value);
var ttoutput;
var display = "";
if( !isNaN(ttinput) ) {
for(var i = 1; i <= 12; i++) {
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
} else {
console.log("value is not a number");
}
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>

HTML --- Javascript/JSON

okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>

Textarea split text into rows and cols

Hi I am working over some textarea which needs to have this kind of functionality: I get in config max lines number and max characters per line number. But I can't think of any algorithm for splitting text into this config values. It would be easy but I have to take into considaration that user can break text by himself and this should be included... Can anyone help me with that?
Please also note that I am not using monospaced font.
I have wrote some code which presents what I am trying to achieve:
splitIntoLines:function (str, lines, maxCharactersPerLine) {
var strLen = str.length,
counter = maxCharactersPerLine,
newStr = '';
if (str.length > 0) {
for (var i = 0; i < strLen; i++) {
newStr += str[i];
counter -= 1;
if (str[i] === '\n' || str[i] === '\r\n' || counter < 0) {
counter = maxCharactersPerLine;
}
if (counter === 0 && this.countLines(newStr) < lines) {
newStr += this.newLine;
}
}
}
if(newStr.length > this.maxChars){
newStr = newStr.substring(0, this.maxChars)
}
return newStr;
}
This function is called every keyUp event. But I think that it isn't best way and it has some bugs.
Simple.. while giving textarea define rows and cols properties to that textarea like
<textarea rows="10" cols="30"></textarea>
try this
<script type="text/javascript">
$(document).ready(function () {
var max_line = 4, max_char = 10;
$('#addAccordion').click(function (event) {
var lines = $('#cmt_content').val().split('\n');
for (var i = 0; i < lines.length; i++) {
if (lines[i].length > max_char) {
alert('character length is more than specified');
}
}
if (lines.length > max_line) {
alert('new line is not allowed');
}
})
});
</script>
<div>
<textarea id="cmt_content" rows="10" cols="60"></textarea>
<br>
<input id="addAccordion" type="button" value="ADD COMMENT" />
</div>

upper case and lower case in text area

I have 2 textarea with maxlenghth of 25:
<textarea row='5' cols='25' maxlength="200" name="address" id="text1"
value="text1" onkeyup="MyFunction()"></textarea>
<br><br>
<textarea row='5' cols='25' maxlength="200" name="address1" id="text2"
value="text2" onkeyup="MyFunction()"></textarea>
If i am entering a lowercase character in 1st textarea,an uppercase character is getting printed and vice versa.But if i am entering a character in second textarea, the answer is not printing in the first textarea. Please help.
function MyFunction() {
var x1 = document.getElementById("text1").value;
var x2 = document.getElementById("text2").value;
var z = '';
for (i = 0; i < x1.length; i++) {
y = x1.charAt(i);
if (y == y.toLowerCase()) {
z = z + y.toUpperCase();
} else {
z = z + y.toLowerCase();
}
}
document.getElementById("text2").value = z;
var z1 = '';
for (j = 0; j < x2.length; j++) {
y1 = x2.charAt(j);
if (y1 == y1.toLowerCase()) {
z1 = z1 + y1.toUpperCase();
} else {
z1 = z1 + y1.toLowerCase();
}
}
document.getElementById("text1").value = z1;
}
you can either do what is described above or you can check which textarea has more characters and simply update the other one
function MyFunction() {
var x1=document.getElementById("text1").value;
var x2=document.getElementById("text2").value;
var z='';
if (x1.length > x2.length)
{
for(i=0;i<x1.length;i++)
{
y=x1.charAt(i);
if(y==y.toLowerCase())
{
z=z+y.toUpperCase();
}
else
{
z=z+y.toLowerCase();
}
}
document.getElementById("text2").value=z;
}
else
{
var z1='';
for(j=0;j<x2.length;j++)
{
y1=x2.charAt(j);
if(y1==y1.toLowerCase())
{
z1=z1+y1.toUpperCase();
}
else
{
z1=z1+y1.toLowerCase();
}
}
document.getElementById("text1").value=z1;
}
}
You call the same function regardless of which textarea the user types in, and that function updates the value of both textareas. Specifically, your function takes whatever was typed in the first textarea, inverts the case of the letters, and writes it to the second textarea. Then, it processes the second textarea the same way, except using the already-updated value as a base.
So when you type in the second textarea whatever was just typed is overwritten before it can be processed.
I'm not entirely clear what your desired behaviour is, but I would guess you intend for typing in either textarea to update the other. The first method that came to mind to achieve that was to split your function into two as follows:
function MyFunction1() {
var x1 = document.getElementById("text1").value;
var z = '';
for (i = 0; i < x1.length; i++) {
y = x1.charAt(i);
if (y == y.toLowerCase()) {
z = z + y.toUpperCase();
} else {
z = z + y.toLowerCase();
}
}
document.getElementById("text2").value = z;
}
function MyFunction2(){
var x2 = document.getElementById("text2").value;
var z1 = '';
for (j = 0; j < x2.length; j++) {
y1 = x2.charAt(j);
if (y1 == y1.toLowerCase()) {
z1 = z1 + y1.toUpperCase();
} else {
z1 = z1 + y1.toLowerCase();
}
}
document.getElementById("text1").value = z1;
}
And then call one the new MyFunction1() from the first textarea and call MyFunction2() from the second:
<textarea row='5' cols='25' maxlength="200" name="address" id="text1"
value="text1" onkeyup="MyFunction1()"></textarea>
<br><br>
<textarea row='5' cols='25' maxlength="200" name="address1" id="text2"
value="text2" onkeyup="MyFunction2()"></textarea>
Demo: http://jsfiddle.net/Ntqq7/

Categories

Resources