Function to Search for a Specified Value Within an Array? - javascript

I am fairly new to JavaScript and StackOverflow and am currently trying to create a function to search for a specialized value within a created array. I have written out what seems like a function that would work, any ideas or any obvious flaws in it? It is currently not working. Thanks!
HTML:
<td>Index: <input style = "width: 50px" input type ="textbox" id="Index" value="2"/></td> <!-- HTML code to create the index textbox -->
<br/> <!-- Line Break -->
Value: <input style = "width: 50px" input type = "textbox" id="Value" value = "10"/> <!-- HTML code to create the value textbox -->
<br />
<td>Enter Value to Find: <input style="width: 50px;" type="textbox" value="20" />
<input type="button" value="Search Array" onClick = searchArray(); /></td>
<br />
<input type = "button" value = "Create" onClick = "createArray();"/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<div id="result">
JS:
var myArray = [];
var d = ""; //This global variable is going to be used for clearing and populating the screen
function createArray (){
//This functions is to clear the current information on the screen so the array can populate
clearScreen();
//The next thing we want to do according to the lecture is create a FOR loop to run 100 times to set the various array values
for (var i = 0; i <100; i++){
myArray[i] = Math.floor(Math.random()* 100 + 1); //Math.floor rounds an number downards to the nearest integer then returns. Math.random returns a integer randomly withing given variables
}
popScreen(); //function to fill the screen with the array
}
function clearScreen(){
d = ""; //Global string variable mentioned before
document.getElementById("result").innerHTML = "";
}
function popScreen(){
for (var i = 0; i < myArray.length - 1; i++){
d += i + ' : ' + myArray[i] + "<br/>";
}
document.getElementById("result").innerHTML = d;
}
function insertIntoArray(){
clearScreen();
var i= parseInt(document.getElementById("Index").value);
var j = parseInt(document.getElementById("Value").value);
d = "inserting " + j+ " at " + i + "<br/>";
var temp = myArray[i];
for (i; i < 100; i++) {
myArray[i] = j;
j = temp
temp = myArray[i+1];
}
popScreen();
}
**function searchArray(myArray, value){
var searchResult = 0;
var searchIndex = -1;
for(var i = 0; i<myArray.length; i++){
searchResult++;
if(myArray[i] == value){
searchIndex = i;
break;
}
}
if (searchIndex == -1){
console.log("Element inquiry not found in array. Total Searched: " + searchResult);
}else{
console.log("Element found at index: " + searchIndex + ", search count: " + searchResult);
}**
}

The issue is caused by the fact there are no arguments passed to the searchArray function via the inline onclick attribute... And they are necessary.
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The error thrown is because myArray is undefined and therefore has no length property.
To have it working, I would modify the HTML from:
<input type="button" value="Search Array" onClick = searchArray(); />
to:
<input type="button" value="Search Array" onClick = searchArray(this); />
And the function would change like this:
function searchArray(element) {
let value = element.previousElementSibling.value
// rest unchanged
searchArray being already defined at global scope, you don't need to pass it.
But you need the value from the input right before the button. You can get it using previousElementSibling.

Related

Using The Input Value Instead Of The First Statement Of A Loop In JavaScript

I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.

Output being not displayed as form data being not rendered (document.getElement)

<html>
<head>
</head>
<body style = "text-align:center;" id = "body">
<form id = "number" method="get" name="number">
<input type="text" id="number1" name="number1" value="" />
<input type="text" id="number2" name="number2" value="" />
</form>
<p id = "GFG_UP1" style = "font-size: 16px;">
</p>
<p id = "GFG_UP2" style = "font-size: 16px;">
</p>
<button onclick = "gfg_Run()">
Convert
</button>
<p id = "GFG_DOWN1" style = "color:red;
font-size: 20px; font-weight: bold;">
</p>
<p id = "GFG_DOWN2" style = "color:red;
font-size: 20px; font-weight: bold;">
</p>
<script>
var form = document.getElementById('number');
var el_up1 = document.getElementById("GFG_UP1");
var el_up2 = document.getElementById("GFG_UP2");
var el_down1 = document.getElementById("GFG_DOWN1");
var el_down2 = document.getElementById("GFG_DOWN2");
var array1 = form.elements.number1.value;
var array2 = form.elements.number2.value;
var numberArray1 = [];
var numberArray2 = [];
for (i = 0; i < array1.length; i++)
{
numberArray1[i] = "Phone" + i + ':'+array1[i];
}
el_up1.innerHTML = "Array = [" +array1+"]";;
a = i;
for (i = 0 ; i < array2.length; i++)
{
numberArray2[i] = "Phone" + a + ':'+array2[i];
a++;
}
el_up2.innerHTML = "Array = [" +array2+"]";;
function gfg_Run(){
el_down1.innerHTML =
JSON.stringify(Object.assign(numberArray1));
el_down2.innerHTML =
JSON.stringify(Object.assign(numberArray2));
}
</script>
</body>
</html>
the following code should give output of two json arrays ["number0:34","number1:24","number2:31","number3:48"]
["number0:23","number1:43","number2:65","number3:52"]
when numbers are given input in the form but no output being shown as in the script both arrays are not able to read data by the form .
error lies in the array as if i pass directly value in array in script it runs fine
help me in debug if u can
I don't think this is a complete answer to your question, but the first thing I notice is that in your for loops, you're trying to use the .length properties of array1 and array2, which aren't actually arrays:
var array1 = form.elements.number1.value;
var array2 = form.elements.number2.value;
You're setting them to the .value properties of the two inputs, which are theoretically going to be digits, but taken as strings by the .value property, because the input type is set to "text".
So Here's what I would do instead:
var form = document.getElementById('number');
var el_up1 = document.getElementById("GFG_UP1");
var el_up2 = document.getElementById("GFG_UP2");
var el_down1 = document.getElementById("GFG_DOWN1");
var el_down2 = document.getElementById("GFG_DOWN2");
/* grab the values from those text inputs, and parse them into integers (because
they will be strings because the input type is set to "text") */
var input1 = parseInt(form.elements.number1.value);
var input2= parseInt(form.elements.number2.value);
/* I also changed the names to input1 and input2 because it's confusing to have them
labeled as 'arrays' when they're actually integers */
var numberArray1 = [];
var numberArray2 = [];
/* now just use those numerical values as your exit condition in your loops */
for (i = 0; i < input1; i++)
{
/* we're also going to use Array.push() to add vlues to the `numberarray` instead of trying to assign a value to the element at "i" */
numberArray1.push("Phone" + i + ':'+ (i+1));
}
/* I'm not 100% sure what you were trying to do here, but I'm guessing that you
actually want to show the values 'numberArray1' here instead of the value of that
first input, so we'll use the 'spread' operator to put that in there */
el_up1.innerHTML = `Array = [${...numberArray1}]`;
a = i;
for (i = 0 ; i < input2; i++)
{
numberArray2.push("Phone" + a + ':'+ (i+1));
a++;
}
el_up2.innerHTML = `Array = [${...numberArray1}]`;
function gfg_Run(){
el_down1.innerHTML =
JSON.stringify(Object.assign(numberArray1));
el_down2.innerHTML =
JSON.stringify(Object.assign(numberArray2));

write a loop into html div with JS

I don't understand why this code is not working, could you help me please ?
I want that when you click on the button, the "theloop" div get filled with yo 0 , yo 1 etc... till the number you inputed
<p>
enter how many time you want the loop to repeat
<input id="nloop">
</p>
</br>
<button onclick="displayLoop()">
Try it
</button>
<p id="theloop"></p>
<script>
var nloop = document.getElementById("nloop").value;
var theloop = document.getElementById("theloop")
function displayLoop () {
for (var i=0; i<nloop; i++) {
theloop.innerHTML = "yo" + i;
}
}
</script>
You have many Syntax error + code error
<p>enter how many time you want the loop to repeat <input id="nloop"></p> </br>
<button onclick="displayLoop()">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop")
function displayLoop(){
var nloop = document.getElementById("nloop").value;
theloop.innerHTML = '';
for (var i=0; i<nloop; i++){
theloop.innerHTML = theloop.innerHTML + "yo" + i+ "<br/>";
}
}
</script>
You need to get the value of nloop when you call the function or the value will be the value when the script is loading, so an empty value.
If you affect something to innerHtml it will erase the content of the innerHtml.
I added BR only for the style you can ignore that.
You missed few syntax checks that I have corrected:
<p>enter how many time you want the loop to repeat <input id="nloop" /></p>
</br>
<button onclick="displayLoop();">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop");
function displayLoop () {
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
theloop.innerHTML = "yo" + i;
}
}
</script>
<script>
function displayLoop()
{
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
document.getElementById("theloop").innerHTML += "yo" + i;
}
}
</script>
This is working fine now :)

Javascript array return "a"?

I wrote this piece with expectancy to store name and score in each and every array element.
Expected output:
var students = [
['David', 80],
['Dane', 77],
['Dick', 88],
['Donald', 95],
['Dean', 68]
];
However, I stumble upon assigning the second value in an array element... In codepen.io, the value returned is "a".
HTML:
name: <input type="text" id="namebox"><br><br>
score: <input type="text" id="scorebox"><br><br>
<input type="button" value="Add" onclick="addStudent()">
<input type="button" value="Display" onclick="displayArray()">
Javascript:
var x = 0;
var students = [];
function addStudent(){
students[x] = document.getElementById("namebox").value;
students[x][1] = document.getElementById("scorebox").value;
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "";
document.getElementById("scorebox").value = "";
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y] + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}
as suggested by #Y.C. if you add students[x][0] = document.getElementById("namebox").value; your code will work. I wanna propose just a minor modification though so that your json array keeps its "pattern". Enclose document.getElementById("scorebox").value in parseInt() so you get the score as a number. In other words just write parseInt(document.getElementById("scorebox").value);
UPDATE
since my previous suggestion only works if you predefine the array I editted the code so now this should work.
instead of assigning the value to each cell I used push() function so now the addStudent method looks like this:
function addStudent(){
students.push(document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value));
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
UPDATE #2
my last update was only for addStudent to work since I thought this was the problem. So now this whole thing has to work by following the steps below:
on your html add a div with the id result because it seems that you forgot
<div id="result"></div>
on your Javascript just copy and paste the following
var x = 0;
var students = [];
function addStudent(){
students.push([document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value)]);
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y][0] + " " + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}
Notice that I have changed the addStudent function a bit just to add every student as a seperate array consisted of his/her name and his/her score.
do something like this
function addStudent(){
var studentArray = [],
tempArray = [],
index= 0;
tempArray[0] = document.getElementById("namebox").value; // David
tempArray[1] = document.getElementById("scorebox").value; //80
// this will insert array into main array.
studentArray.push(tempArray); // [['David', 80]]
// rest of your code
return studentArray;
}

Sum of form input in Javascript

I want the user to enter a number then when it is submitted, it is inserted into the array totalBags.
The user can then submit another number, when submitted the array elements are added together.
E.g. Input = 2
Press submit
Output = 2
New input = 3
Press submit
Output = 5
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitOrder()
{
var allBags = [];
var bags_text = document.getElementById("bags").value;
allBags.push(bags_text);
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i]; // here is the problem... i think
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
function resetOrder()
{
document.getElementById("container").innerHTML = "<p><label for=\"bags\">No. bags: </label><input type=\"text\" id=\"bags\" /></p><p><input type=\"button\" value=\"Subit order\" onClick=\"submitOrder()\"> <input type=\"reset\" value=\"Reset Form\" /></p>";
}
</script>
</head>
<body>
<form name="order_form" id="order_form">
<div id="container">
<label>Total bags: </label><input id="bags" type="text" ><br>
<input type="button" id="submitButton" value="Subit order" onClick="submitOrder()">
<input type="reset" value="Reset" class="reset" />
</div>
</form>
</html>
I should rewrite the program a bit. First, you can define global variables which won't be instantiated in the function. You are doing that, which resets the variables. Fe
function submitOrder()
{
var allBags = [];
// ...
}
It means that each time you're clicking on the button allBags is created as a new array. Then you add an value from the input element. The result is that you have always an array with one element. It's best to declare it outside the function. By this, you ensure that the variables are kept.
// general variables
var allBags = [];
var totalBags = 0;
function submitOrder()
{
// the result is a string. You have to cast it to an int to ensure that it's numeric
var bags_text = parseInt(document.getElementById("bags").value, 10);
// add result to allBags
allBags.push(bags_text);
// total bags
totalBags += bags_text;
// display the result
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
by leaving out the loop, you have an more performant program. But don't forget to clear the array and the totalBags variable to 0 if you're using the reset button.
function resetOrder()
{
document.getElementById("container").innerHTML = "...";
// reset variables
totalBags = 0;
allBags = [];
}
Try to use:
for (var i = 0; i < allBags.length; i++)
{
totalBags += parseInt(allBags[i],10);
}
Or use Number(allBags[i]) if you prefer that.
Your element allBags[i] is a string and + between strings and concatenting them.
Further study: What is the difference between parseInt(string) and Number(string) in JavaScript?
function submitOrder()
{
var allBags = parseInt(document.getElementById("bags").value.split(""),10);//Number can also used
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i];
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}

Categories