For Loop Only Running Through Once - javascript

In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>

tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.

Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

See what changed inside TextArea with on change listener

I need a textbox, where everytime the text changes, I know what exactly has changed. I'm currently using a JQuery's listener for changes in my input element, and what I do is:
When the text changes
Get the text from the box a1 and compare to what I have in box a2.
If there are changes, log them into output textarea
Here is a Sample https://codepen.io/nikolaevra/pen/eeWWbo
I'm currently using the following diff library https://github.com/kpdecker/jsdiff, and it has O(NM) efficiency, which is a lot.
Is there a way to get the exact change that was made to the textarea using JQuery or anything like that? For example, if I had test in both a1 and a2 and then changed a1 to be testing, I want to see ing as the change that was made.
EDIT:
I tried playing around with the method a little bit and this is one problem that I found. When I run diff = "testing".replace("test",''); => ing just as required, but when I try diff = "testing a potato cannon".replace("testing potato cannon",''); => testing a potato cannon, where I only changed one character. This is a lot of overhead that I wanted to avoid. In that case, I would only want to know where the value has been changed and what it has been changed to. Not the entire tail of the string.
Consider that what you have in string a1 is the constant text and that what you have in string a2 is where you make changes.
let's just say that the value in a1 is "test";
Try this for your JavaScript:
var constValue = $('#a1').val();
$('#a2').change(function() {
var changingValue = $('a2').val(); // say the value entered is "testing"
console.log(changingValue.replace(constValue, ''); // gives you "ing"
}
This will give you the changed/entered (newly) value in string a2 and log it to your console.
The logic you use here is simple:
Read the value from string a2 and use the value in a1 to replace (if exists) in string a2, hence giving you the changed value. You need not use any libraries for this. JavaScript gives you this function called replace.
Do let me know if any more queries.
nikolaevra, have you tried using javascript's replace method? e.g diff = [value of a1].replace([value of a2],'');
You can use this method to achive what you are looking for :
function getDifference(a, b)
{
var i = 0;
var j = 0;
var result = "";
while (j < b.length)
{
if (a[i] != b[j] || i == a.length)
result += b[j];
else
i++;
j++;
}
return result;
}
Then you need to make a method to get the values from your textboxs and use it in your button onclick event, I used javascript, you can use jquery if you want :
function findDiff(){
var b1= document.getElementById("b1").value;//sky is blue
var b2= document.getElementById("b2").value;//sky is red
document.getElementById("result").value=getDifference(b1,b2);//red
}
https://jsfiddle.net/eu2kvfxo/
i hope this code will help you
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var arr_text1 = new Array();
var arr_text2 = new Array();
var i=0;
var text2nw="";
$('#a2').on('input',function () {
arr_text1 = $("#a1").val().split('');
arr_text2 = $("#a2").val().split('');
if (arr_text1[i] == arr_text2[i]) {
}
else {
$('#output').val($("#a2").val().replace($("#a1").val(), ""));
// $('#output').val(text2nw);
}
if ($("#a2").val() != '') {
i++;
}
else {
i = 0;
$('#output').val('');
}
});
});
</script>
</head>
<body>
<p>This is the original text:</p>
<textarea id="a1" rows="4" cols="50" type="text"></textarea>
<p>Change Text to something else here:</p>
<textarea id="a2" rows="4" cols="50" type="text"></textarea>
<p id="title">This are the changes that you made:</p>
<textarea rows="10" cols="100" id="output" for="title"></textarea>
</body>
</html>

get input value using javascript and based on its value use javascript to insert a value elsewhere

I have this loading at the bottom of the page
if((document.getElementById('pcc').value)==="1") {
var $postcontrr = "hello";
document.write($postcontrr);
}
else {document.write ('this is messed up');}
in my form I have a field with id=pcc so the way I'm reading it is, if the value of field with id of pcc is 1 the the varialbe $postcontrr is going to be Hello and then the document.write should print Hello. But I get nothing. Not even the else statement prints. Any pointers would be appreciated.
Get the expected result. No error here.
Please check it out in
if ((document.getElementById('pcc').value) === "1") {
var $postcontrr = "hello";
document.write($postcontrr);
} else {
document.write('this is messed up');
}
<html>
<input id="pcc" value="1" type="text" />
</html>
I would make you javascript into a function so you can call it onkeyup of the input. I would also change the inner html of an element instead of using document.write otherwise you will just be appending the text to the document each time the input changes.
<script>
function checkValue() {
var $postcontrr;
if (document.getElementById('pcc').value === "1") {
$postcontrr = "hello";
} else {
$postcontrr = "this is messed up";
}
document.getElementById('result').innerHTML = $postcontrr;
}
</script>
<input type="text" id="pcc" onkeyup="checkValue();">
<div id="result"></div>

While loop and innerHTML

I'm not sure if there is something wrong with my while loop or the innerHTML section of my code but I'm not able to show the drop down lists in the div tags when the submit button is clicked. Can anyone see whats wrong with it.
<html>
<head>
<script type="text/javascript">
function getvalue() {
number = document.getnumber.input.value;
document.getElementById("result").value = number;
}
</script>
</head>
<body>
<script>
function generatedropdown() {
html = '<select name="select" id="i">';
while (i < number) {
html+='<option>Test 1</option>';
html+='<option>Test 2</option>';
html+='<option>Test 3</option>';
html+='<option>Test 4</option>';
html+='<option>Test 5</option>';
i++;
}
html+='</select>';
document.getElementById("my-output").innerHTML = html;
}
</script>
<form name="getnumber">
Input number: <input type="text" name="input">
<input type="button" value="Next" onClick="getvalue()">
</form>
<form id="showlists">
Number entered: <input type="text" id="result" readonly="readonly">
<input type="button" value="Show lists" onClick="generatedropdown()">
<div id="my-output">Generated List:</div>
</form>
</body>
</html>
A few problems:
You've never set an initial value for i, so the code will throw an error, since you're trying to read the value of a global that you've never set or declared.
You're relying on getvalue having been called to initialize number, which I wouldn't count on.
You're relying on implicit string -> number conversion, which I don't recommend; use parseInt to parse numbers supplied by users.
(Optional) Your loop is exactly what the for construct is designed for, rather than while (although while would work if you initialized i).
You're falling prey to The Horror of Implicit Globals because you're never declaring your variables.
I suggest reading a good primer or tutorial on JavaScript, to master the basics.
Here's a minimal update:
function generatedropdown() {
// Declare your variables
var html, i, number;
// Get the number, and convert it from a decimal string
// to a number explicitly rather than relying on implicit
// coercion
number = parseInt(document.getvalue.input.value, 10);
// Probably bail if it's not a number
if (isNaN(number)) {
return;
}
// (Optional, but you were doing it) Show the number
document.getElementById("result").value = number;
// Build your HTML
html = '<select name="select" id="i">';
// This is exactly what `for` loops are for
for (i = 0; i < number; ++i) {
html+='<option>Test 1</option>';
html+='<option>Test 2</option>';
html+='<option>Test 3</option>';
html+='<option>Test 4</option>';
html+='<option>Test 5</option>';
}
html+='</select>';
document.getElementById("my-output").innerHTML = html;
}

Returning HTML Ends Loop Premature

I am using javascript to validate some form elements. The fields I want to be required are passed into my validateReqFields function when the form is submitted. Everything is working perfectly until I get to the for loop that is meant to add an error message the an empty beside the form field. It seems that as soon as one field fails and it adds the message to the div, the for loop does not continue.
The HTML Form Elements:
First Name <input type="text" name="firstName" onkeypress="return checkField(event, letters);"/><div id="firstNameMsg" style="display:inline-block;"></div>
<br>
Last Name <input type="text" name="lastName" onkeypress="return checkField(event, letters);"/><div id="lastNameMsg" style="display:inline-block;"></div>
The Javascript function:
function validateReqFields(formName, reqFields){
var fieldArray = reqFields.split(",");
var failedList = new Array();
var message = "Required Field";
for(var i=0; i<fieldArray.length; i++){
removeWhiteSpace(fieldArray[i]);
var s = eval('document.'+formName+'.'+fieldArray[i]+'.value');
if(s.length<1) { failedList.push(fieldArray[i]); }
}
if(failedList.length >= 1) {
for(var i=0; i<failedList.length; i++) {
//BUG - Only shows first failed field.
document.getElementById(failedList[i] + 'Msg').innerHTML = message;
}
} else {
document.mForm.submit();
}
}
function removeWhiteSpace(mString){
mString = mString.replace(/(^\s+|\s+$)/g,' ');
return mString;
}
I have done a few tests and concluded that when the for loops sets the innerHtml on the first div element, it breaks the for loop. Is there a way to avoid this?
My removeWhiteSpace function was not working correctly, thus everything after my first field was failing. Silly mistake. Please close this question.

Categories