Re-feeding a variable into a looped function - javascript

I'm attempting to make a simple program for encoding things in base64 multiple times (not really for any particular reason, just more as an example and practice). I've been having quite a bit of trouble though, it could be because I've not had enough (or possibly had too much) coffee.
I can't seem to figure out how to refeed my variable (text) back into the function that encodes it until i is equal to times
Any assistance with this would be appreciated!
<html>
<head>
<script>
function encodeThis(text,times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
</script>
</head>
<body>
<b>Text to Encode</b><br/>
<input type="text" id="encode"><br/>
<b>Number of Times to Encode (Integers Only)<br/>
<input type="text" id="times">
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">
</body>
</html>
Would I need to put a function inside of that function to refeed the variable in?

You need to assign the result of the encoding back to the variable.
function encodeThis(text, times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
But in terms of the overall code in your example you also need to actually get the text from the #encode and the #times elements and fix the syntax error in the for loop.
So
function encodeThis(text, times) {
var toEncode = text.value, // read the value from the encode input element
numTimes = parseInt(times.value, 10); // read the value from the times element and convert to number
for (var i = 0; i < numTimes; i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
<b>Text to Encode</b><br/>
<input type="text" id="encode" /><br/>
<b>Number of Times to Encode (Integers Only)</b><br/>
<input type="text" id="times" />
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How to take input at terminal in JavaScript

How can I take input at terminal
Here the first line contain an integer (the size of my array).
The second line contains integers that describe array 's elements.
I used
window.prompt()
but it take input only in browser. How can I take input in terminal
function arrayAction(A, N) {
var temp = []
var r = window.prompt(N)
for (var i = 0; i < r; i++) {
temp.push(window.prompt(A))
temp.reverse();
}
console.log(temp)
}
arrayAction()
if you want to take input you should use this small html and javascript code
var a = document.getElementById("hello").value;
alert(a);
<input id="hello" type="text">
<span="hi"your number is</span>
<p></p>
var num=document.getElementById("hello")
var te=document.getElementById("out")
function demo(){
te.innerHTML=num.value;
//document.write(num.value);
}
<input id="hello" type="number" >
<button onclick="demo()">Click me to get your input number</button>
<br>
<span id="hi">your number is</span>
<p id="out"></p>

I need to find the longest word in a sentence using JS

I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>
var btn = document.getElementById("btn1");
var in1 = document.getElementById("input1");
var sp1 = document.getElementById("sp1");
btn.onclick = function(){
var vals = in1.value.split(' ');
var val = vals[0];
vals.forEach(function(v){ if(v.length>val.length) val = v;});
sp1.textContent = val;
}
</script>
Fiddle Demo
Add this to your button:
onClick="alert(longestWord(document.getElementById('input1').value))"
It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.
I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)
Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)
None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"

echo five times a input with jQuery

How is repeated code HTML for five times?
like repeated(echo) a input <input type="text" name="ok"> with a js code five times.
I mean this is that, a input by a js code echo five times
I want after run jQuery code output is this (5 input):
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
how is it?
Your question isn't totally clear, do you mean this?
for (var i = 0; i<5;i++) {
$("body").append("<input type='text' name='ok'>");
}
function EchoInput(html, count) {
var result = [];
for (var i = 0; i < count; i++)
result.push(html);
return result.join("");
}
To use this function, you could do something like this:
document.write(EchoInput("<input type='text' name='ok'>", 5));
var body = $('body');
for(var i = 0; i < 5; i++) {
body.append('<input type="text" name="ok">');
}
http://jsfiddle.net/ucbsh/1/
Instead of creating HTML, you can create elements directly.
Here is a way that let you set different names on each input field. Right now all five have the name "ok", but you can change that in the array:
// use ready event so that the page is loaded:
$(document).ready(function(){
// decide where to add the elements:
var container = $('body');
// loop over an array of names:
$.each(['ok','ok','ok','ok','ok'], function(idx, name) {
// create an element and add to the container:
container.append($('<input/>', { type: "text", name: name }));
});
});

creating a for-loop using Javascript?

I have a problem creating a for-loop using Javascript. It seems everyting is fine for me but still I didn't get what I want.
Take a look please to this code to understand more:
The HTML form code:
<form name="myform">
<textarea name="inputtext" cols="100%" rows="10%"></textarea><br />
<input type="radio" name="options" value="javascript" checked> Option1 <br />
<input type="radio" name="options" value="windows"> Option2<br />
<input type="button" value="Do it" onClick="generate();"><br />
<textarea name="outputtext" cols="100%" rows="10%"></textarea><br />
</form>
The Javascript code:
function generate() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
for(int i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
The problem is not clear for me.
However, when I try to comment out the for-loop, everything works fine !
Any ideas?
There is no int data type in Javascript (or any data types at all used to declare variables).
for(var i=0; i<code.length; i++) {
There is also an Object-oriented solution to this.
var generate = {
loop: function() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
//CHANGE THE INT(I assume Java) DATATYPE TO A LOCAL VARIABLE USING THE var KEYWORD TO KEEP THE SCOPE IN THE FOR LOOP
//RECURSION CAN BE QUICKER
for(var i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
generate.loop();

Categories

Resources