Below is my code. I need to sort the array after the user input but can't figure out how to make that happen. I have tried several different things but nothing has worked including data.sort() and data.sort(function(a,b) { return a - b; }); but neither seems to be working. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Input integers into the array and then search the array to see if your input is present!</h1>
<p id="data">[]</p>
<input id="inputNumber" value="0" /> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0" /> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
for (var i = 0; i < 5; i++) {
data.push(prompt('enter integer ' + (i + 1)));
}
alert('Full array: ' + data.join(', '));
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for (var i = 0; i < data.length; i++) {
if (data[i] == toFind) return alert("found at " + i);
}
return alert("That number was not found");
}
function refresh() {
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>
Related
So my problem is that putting onclick="main()" onto a button doesn't work but something like onclick="alert('test')" does work. When I look in the console, it throws Uncaught ReferenceError: main is not defined when I press the button.
I have tried putting all the functions that aren't main() inside of main() but that didn't work. I've also tried putting semicolons after all the functions thinking that I just made up the fact that you don't have to put a semicolon after a function.
I'm confused because I copy/pasted another JavaScript program of mine and edited it to make this and that one works fine.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
<style>
/*----- START OF STYLESHEET -----*/
*, :before, :after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*body {
margin : 0;
*/}
/*-----END OF STYLESHEET-----*/
</style>
<script>
//----- START OF SCRIPT -----//
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shuffle-list() {
for(var shuffleent = 0; shuffleent > list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display-list() {
var state = "";
for(displayent = 0; displayent > list.length; displayent = displayent + 1) {
for(displayentvalue = 0; displayentvalue > list[displayent]; displayentvalue = displayentvalue + 1) {
state = state + "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
Sleep(1000);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display-list();
// Shuffle sorted list
// Sort
//while(isSorted === false) {
//}
}
//-----END OF SCRIPT-----//
</script>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
some error in you code:
"}"
'-' in the function name.
after fixed the error, the code worked
You should not use a - while naming your function but instead you can use these.
An underscore and replace the -.
display-list() to display_list()
Use CamelCase.
display-list() to displayList().
Function names can contain letters, digits, underscores, and dollar signs but not dash
sign
There are so many mistakes in your code.
There is no Sleep function in the JS.
You can't have - or whitespaces in the function names.
You are never going to enter in this loop for(displayent = 0; displayent > list.length; displayent = displayent + 1) you had to use < instead >
Where are you using valuecount and isSorted
In the CSS } which shouldn't be there
I edited some of your code to make it work.
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shufflelist() {
for (var shuffleent = 0; shuffleent < list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display_list() {
var state = "";
for (displayent = 0; displayent < list.length; displayent = displayent + 1) {
for (displayentvalue = 0; displayentvalue < list[displayent]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
Re Wrote the logic of your code
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
list[value2] = [list[value1], list[value1] = list[value2]][0];
}
// Shuffle list
function shufflelist() {
list.forEach((element, index) => {
swap(index, randint(0, list.length))
})
}
// Display list
function display_list() {
var state = "";
list.forEach((element, index) => {
for (displayentvalue = 0; displayentvalue < list[index]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state += "\n"
})
console.log(state);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
shufflelist();
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
In this prototype, I have "products" that are each individually stored in a div along with their price. I have added four buttons that sort the divs containing the products in alphabetical order (A-Z AND Z-A) as well as by price (lowest to highest and highest to lowest). These sorting functions work perfectly by themselves. I also have a search bar that acts as a search engine if you like an upon entering each character into the input field, will eliminate the products (div's) by name if they do not contain that letter(s). I have done this using a regular expression. This also worked by itself until I adapted it to try and work in conjunction with the sorting mechanisms.
Problem
I would like to be able to search for "products" using the search functionality to display the correct results regardless of what order the products have been sorted into.
Question
How is it possible to be able to display only the div's that contain the letter(s) searched for in the search bar regardless of the ordering (e.g. Z to A).
I think I ruined the search function itself by adding the index variable but you can't do list.name[i].match(res) can you? There is something wrong with the logic behind the search function. I believe the function that needs serious fixing is the searchProducts function.
The code AFTER I adapted the searchProducts function is below...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="resultsSpan"></div>
<div id="product0" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product1" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product2" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product3" style="height:60px; width:60px; background-color:blue;"></div>
<button onclick="sortprods()">
Sort A-Z
</button>
<button onclick="sortprods2()">
Sort Z-A
</button>
<button onclick="sortprods3()">
Price (low to high)
</button>
<button onclick="sortprods4()">
Price (high to low)
</button>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
</body>
</html>
<script>
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
list.sort(AtoZ);
for (var i = 0; i<list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
function AtoZ(a,b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
function ZtoA(a,b) {
if (a.name < b.name)
return 1;
if (a.name > b.name)
return -1;
return 0;
}
function LowtoHigh(a,b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function HightoLow(a,b) {
if (a.price < b.price)
return 1;
if (a.price > b.price)
return -1;
return 0;
}
function sortprods(){
list.sort(AtoZ);
currentSort = "AtoZ";
for (var i = 0; i < list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
}
function sortprods2(){
list.sort(ZtoA);
currentSort = "ZtoA";
for (var j = 0; j < list.length; j++) {
document.getElementById("product" + j).innerHTML = list[j].name + ", " + list[j].price;
}
}
function sortprods3(){
currentSort = "LowtoHigh";
list.sort(LowtoHigh);
for (var k = 0; k < list.length; k++) {
document.getElementById("product" + k).innerHTML = list[k].name + ", " + list[k].price;
}
}
function sortprods4(){
currentSort = "HightoLow";
list.sort(HightoLow);
for (var l = 0; l < list.length; l++) {
document.getElementById("product" + l).innerHTML = list[l].name + ", " + list[l].price;
}
}
var input = "";
var index = [];
var currentSort = "AtoZ";
function searchProducts(){
input = document.getElementById("searchbar").value;
if(input == ""){
document.getElementById("product0").style.display = "block";
document.getElementById("product1").style.display = "block";
document.getElementById("product2").style.display = "block";
document.getElementById("product3").style.display = "block";
}else{
switch(currentSort){
case "AtoZ":
list.sort(AtoZ);
for(var a = 0; a < list.length; a++){
document.getElementById("product" + a).innerHTML = list[a].name + ", " + list[a].price;
index.push(list[a].name);
}
index.sort();
break;
case "ZtoA":
list.sort(ZtoA);
for(var b = 0; b < list.length; b++){
document.getElementById("product" + b).innerHTML = list[b].name + ", " + list[b].price;
index.push(list[b].name);
}
index.sort();
index.reverse();
break;
case "LowtoHigh":
list.sort(LowtoHigh);
for(var c = 0; c < list.length; c++){
index.push(list[c].price);
}
index.sort(function(a, b){return a-b});
break;
case "HightoLow":
list.sort(HightoLow);
for(var d = 0; d < list.length; d++){
index.push(list[d].price);
}
index.sort(function(a, b){return b-a});
break;
}
test = input;
re = new RegExp(test, 'gi');
for(var e=0; e<index.length; e++){
if(index[e].match(re)){
document.getElementById("product"+e).style.display = "block";
}else{
document.getElementById("product"+e).style.display = "none";
}
}
}
}
</script>
The code before I adapted the searchProducts function (THAT WORKED PERFECTLY BEFORE ADAPTION) is...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
<div id="demo"></div>
<div id="demo2">
<div id="product1" style="background-color:red; height:100px; width:100px; float:left">chocolate<br /><button onClick="grow()" id="button1">Show Info</button></div>
<div id="product2" style="background-color:blue; height:100px; width:100px; float:left">Mint</div>
<div id="product3" style="background-color:green; height:100px; width:100px; float:left">Caramel</div>
</div>
</body>
</html>
<script>
var index = ["Chocolate", "Mint", "Caramel"];
var input = "";
var currentLog = [];
function searchProducts(){
currentLog = [];
input = document.getElementById("searchbar").value;
/*function searchStringInArray(str, strArray){
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)){
var temp = strArray.slice(j, (j + 1));
currentLog.push(temp);
console.log(j);
}
}
document.getElementById("demo").innerHTML = currentLog.join("<br />");
if(currentLog.length < 1){
document.getElementById("demo").innerHTML = "No results were found.";
}
}*/
test = input;
re = new RegExp(test, 'gi');
/*if(!index[0].match(re)){
document.getElementById("product1").style.display = "none";
}
if(!index[1].match(re)){
document.getElementById("product2").style.display = "none";
}
if(!index[2].match(re)){
document.getElementById("product3").style.display = "none";
}*/
for(var e=0; e<index.length; e++){
if(!index[e].match(re)){
document.getElementById("product"+(e+1)).style.display = "none";
}else{
document.getElementById("product"+(e+1)).style.display = "block";
}
}
if(document.getElementById("product1").style.display == "none" && document.getElementById("product2").style.display == "none" && document.getElementById("product3").style.display == "none"){
document.getElementById("demo").innerHTML = "no results";
}else{
document.getElementById("demo").innerHTML = "";
}
/*searchStringInArray(input, index);*/
}
function grow(){
if(document.getElementById('product1').style.height == "200px"){
document.getElementById('product1').style.height = '100px';
document.getElementById('button1').innerHTML = "Show Info";
}else{
document.getElementById('product1').style.height = "200px";
document.getElementById('button1').innerHTML = "Hide Info";
}
}
</script>
The issue is that when you sort your list when a filter was applied earlier, you only move the data, not the visibility of the containers of those data.
Instead you could re-execute the regex matching, every time you display the content according to the current sort order. That way you are sure the right data are visible at all times.
You have a lot of duplication in your code, with several places where you have the same loop, or code that only differs in one aspect. You should always try to "Don't Repeat Yourself" (DRY).
I would suggest to have one function for displaying content only. You could pass it the sort function to apply. Note that this means the HTML also changes where you have specified the event handlers. There are many other such simplifications, which are too many to mention all.
Check this snippet:
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
var currentRegex = /./; // any character matches
var currentSort = AtoZ;
// Call the function we have for applying the initial sort order and filter
searchProducts(document.getElementById('searchbar').value);
// Shorter ways to compare:
function AtoZ(a,b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }
function ZtoA(a,b) { return AtoZ(b,a) }
function LowtoHigh(a,b) { return a.price - b.price }
function HightoLow(a,b) { return b.price - a.price }
// One function for all sort orders: pass sort order as function
function sortprods(sorter) {
var showCount = 0;
currentSort = sorter;
list.sort(currentSort);
for (var i = 0; i < list.length; i++) {
var product = document.getElementById("product" + i);
// use textContent, not innerHTML
product.textContent = list[i].name + ", " + list[i].price;
var show = !!list[i].name.match(currentRegex);
product.style.display = show ? "" : "none";
showCount += show;
}
document.getElementById('resultsSpan').textContent =
showCount ? '' : 'no results';
}
function searchProducts(input){
// Argument is value of input
// No need to `switch` on currentSort. Can do this with generic code.
// Deal with empty input by using all-matching `.` regexp.
// `g` not needed.
currentRegex = new RegExp(input.length ? input : '.', 'i');
sortprods(currentSort);
}
<div id="resultsSpan"></div>
<div id="product0" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product1" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product2" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product3" style="height:45px; width:60px; background-color:lightblue;"></div>
<button onclick="sortprods(AtoZ)">Sort A-Z</button>
<button onclick="sortprods(ZtoA)">Sort Z-A</button>
<button onclick="sortprods(LowtoHigh)">Price (low to high)</button>
<button onclick="sortprods(HightoLow)">Price (high to low)</button>
<input type="text" id="searchbar" onkeyup="searchProducts(this.value)"/>
About the ternary operator:
You asked in comments about the ternary operator:
product.style.display = list[i].name.match(currentRegex) ? "" : "none";
The above is equivalent to this:
var temp;
if (list[i].name.match(currentRegex)) {
temp = "";
} else {
temp = "none";
}
product.style.display = temp;
... except that no temp variable is created of course.
The other occurrence:
currentRegex = new RegExp(input.length ? input : '.', 'i');
... is equivalent to:
var temp;
if (input.length) { // if length is defined and not 0
temp = input;
} else {
temp = ".";
}
currentRegex = new RegExp(temp, 'i');
<html>
<script>
var tal;
var array = [];
var element=parseIFloat();
function bubbleSort(A){
var swapped,
len = A.length;
if(len === 1) return;
do {
swapped = false;
for(var i=1;i<len;i++) {
if(A[i-1] > A[i]) {
var b = A[i];
A[i] = A[i-1];
A[i-1] = b;
swapped = true;
}
}
}
while(swapped)
}
function insertnumber(){
var element=document.getElementById("element").value;
insert (element,array);
}
function insert(element, array) {
array.push(element);
alert(array);
bubbleSort(array);
alert(array);
}
</script>
<body>
<input type="button" value="Mata in" onclick="insertnumber()" id="resultat">
tal<input type="number" id="element" autofocus>
</body>
</html>
This my code but i really dont know how to get it working again, my problem is that i cant get it to read numbers correctly, trying to use "var element=parseIFloat(); " but that doesnt seem to work..
Thanks :)
Sure, var element=parseIFloat();
was meant to be var element=parseFloat();
and put between
var element=document.getElementById("element").value;
and
insert (element,array);
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>
So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example