How to loop in JavaScript - javascript

DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.

with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));

You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.

Related

Use slice(); method to achieve an arithmetic operation

My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>

Uncaught ReferenceError: Invalid left-hand side in assignment. Javascript

I want to replace a character in a string (original) with another string.
I am getting an error on running the debugger.
I dont understand what is wrong with the syntax.
<!DOCTYPE>
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string<input id="original" value="" type="text"> <br>
Enter the replacing string<input id="replacing" value="" type="text"><br>
Enter the location to be replaced<input id="tobereplaced" value="" type="text"><br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br> Here you go the replaced string is:
<script>
function replace() {
var original = document.getElementById("original").value;
var replacing = document.getElementById("replacing").value;
var tobereplaced = document.getElementById("tobereplaced").value;
var replaced = "";
var originalLength = original.length;
var tobereplacedLength = tobereplaced.length;
var k = 0;
for (var i = 0; i < originalLength; i++) {
replaced.charAt(k) = original.charAt(i)
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
k = k + tobereplacedLength;
i++;
}
k++;
}
document.getElementById("replaced").innerHTML = replaced;
}
</script>
<h1 id="replaced"></h1>
</body>
</html>
you are trying to change the character of an empty string at line no:28 [replaced.charAt(k) = original.charAt(i)] this is the issue.
Also there are some unwanted increment in the code. please find the corrected below
I have updated the code below with // comment the code and added correct code. its working
// var k = 0; //Commented
// debugger; //Commented
for (var i = 0; i < originalLength; i++) {
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
// k = k + tobereplacedLength; //Commented
// i++; //Commented
} else{
replaced = replaced + original.charAt(i);
}
// k++; //Commented
}
Here is a more simplistic approach to the problem. It takes advantage of the .split() & .join() functions rather than using a for loop.
function replace() {
// set original string
var original = document.getElementById("original").value, // << use commas so you don't have to keep typing var
// set replacing string
replacing = document.getElementById("replacing").value,
// initialize newval
newValue,
// set replace position - this could also be called index
replacePosition = document.getElementById("tobereplaced").value; // << end variable declarations with semicolon
// split original string into array of characters
var splitOriginal = original.split("");
// use replacePosition as index value of character to replace
// & replace that character with replacing value
splitOriginal[replacePosition] = replacing;
// join array to form new string value
newValue = splitOriginal.join("");
document.getElementById("replaced").innerHTML = newValue;
}
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string
<input id="original" value="" type="text">
<br>Enter the replacing string
<input id="replacing" value="" type="text">
<br>Enter the location to be replaced
<input id="tobereplaced" value="" type="text">
<br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br>Here you go the replaced string is:
<h1 id="replaced"></h1>
</body>
</html>

Modifying the integer at the end of a string

I am in need of your assistance,
What I need is a javscript function that would accomplish one of two things:
Firstly, if given a string, ie. var x = "filenumber" the function when called, would process the string and add a -2 to the end of it, resulting in var x = "filenumber-2" if the -2 does not exist on the end of the string.
Secondly, if the given value, var x is already = "filenumber-2" then take the number at the end of the string and increment it by 1, resulting in var x = "filenumber-3". and so fourth incrementing the number every single time after that, if the function is called again.
Here is the concept markup:
<DOCYTPE HTML>
<html>
<head>
<script type="text/javascript">
function test(){
var x = document.getElementById('input').value
1.) if x doesnt already have the -2 at the end of the string then add it:
document.getElementById('output').value = x + "-2"
2.) else, the function recognizes that it does and the result of the output is
x-2 + 1
}
</script>
</head>
<body>
<input type="text" id="input"/>
<br>
<input type="text" id="output"/>
<br>
<input type="button" onclick="test()" value="test"/>
</body>
</html>
Short 'n sweet:
x = 'filenumber-4';
x = x.replace(/^(.+?)(-\d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );

Javascript change text of all inputs

I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}

Hidden input field

I have an array with 8 elements defined within a script.
I'd like to know how I can pass all the values of this array to a single hidden element.
Pls help.
<script ='text/javascript'>
function abc(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= ...;
}
</script>
<input type="hidden" id="arrs" name="arrs" value= ? >
you can join them with comma ','
$('#arrs').val(arr.join(','));
From the comments on the question itself
I will have to access this input
hidden element in another js later on
using document.forms.element(''). so
thought it would be easier using a
single element.
It would be easiest to not use any form element at all. Not sure why you want to take such a detour. You have a JavaScript variable, you can use that directly in "another script later on":
<script type="text/javascript" id="firstScript">
function abc(){
var arr = [];
for (var i=0; i<8; i++) {
arr.push(...);
}
return arr;
}
var myArray = abc();
</script>
<!-- time passes, but we're still on the same page... -->
<script type="text/javascript" id="anotherScript">
doSomethingWith(myArray);
</script>
You can try like this:
<script>
function a(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= i;
}
document.getElementById('d').value = arr;
alert(document.getElementById('d').value);
}
</script>
<input id="d" type="hidden" />
<input type="button" onclick="javascript:a();" value="A" />
Hope this helps.
If the values are only strings or integers, you can try joining them with a seperator not present in your input:
document.getElementById("arrs").value = arr.join("###");
And you can do
myArr = document.getElementById("arrs").value.split("###");
To retreive that array back.

Categories

Resources