Uncaught SyntaxError: Unexpected end of input false error [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Just The last "}" shows a error for no reason.
A "}" is a death?
VIIIth attempt.
A coding job makes my brain kinda melt.
Send help! I am freaking out!
Can't fix this.
Return 1;
I am almost losing my mind.
Pot of 1 and 0s'.
Thanks if you read this btw just read the first letter on the first words on start of the sentences.
console.error("1010101 011110 1010101010 1001 0101010100 1001 010001001");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(29));
}
document.getElementById("submit").onclick = function() {
console.log("Submitted prize. Prize ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(27));
}
document.getElementById("acceptpol").onclick = function() {
console.log("Accepted promise. Promise ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(29));
}
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(11));
}
h1{
color: green;
}
label{
color: green;
}
input{
color: green;
}
body,html{
height: 100%;
margin: 0;
background-image: url('smile.jpg');
background-position: center;
background-size: cover;
}
<html>
<body>
<h1> Press F12 in your keyboard to see your promise, submit and your contact ID </h1>
<h1> ENTER YOUR INFORMATION TO CLAIM YOUR PRIZE! </h1>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname" id="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="emailadd">E-Mail Address (So we can contact to you):</label>
<input type="text" id="emailadd" name="emailadd"><br><br>
<label for="address">Your Home Address</label>
<input type="text" id="address" name="address"><br><br>
<input type="checkbox" id="acceptpol">accept to contact to us when your prize when it's not in your address</input>
<input id="submit" type="submit" value="Submit"></input>
</body>
<head>
<title> TriviaAwards.com </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
</html>

You are missing 2 closing brackets in your javascript you don't close the document.getElementById functions:
document.getElementById("submit").onclick = function() {
console.log("Submitted prize. Prize ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(27));
}
} // add this
Same for the other getElementById function.
If you keep your indentation the same you can prevent these errors.

Related

If statement with OR condition not working

I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>

Prime checking program not working on certain numbers

I was excited because my prime number program was working, but when I tried certain numbers like 5 and 10, 2 and 11, it wasn't working. I have tried to figure it out myself, and by looking at other things related to what I was doing, but I couldn't figure it out. I would appreciate an answer and thank everyone who helps, because I am just a beginner at coding and want to learn more.
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = document.getElementById('Minimum').value;
maximum = document.getElementById('Maximum').value;
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
Your code for calculating a prime looks fine. The problem is that you are using the raw strings from the minimum and maximum to create your range. The problem is that strings are compared lexigraphically, so:
"2" < "100" // false
So when you pass those values into your function listOfPrimes, that loop will terminate early due to the string comparison.
To fix it, just convert your input values to numbers before you use them:
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
Here's your snippet with that fix, everything looks like it's working well:
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
PS: You can further optimize your isPrime function by only checking divisors up to Math.floor(Math.sqrt(num)). That will save you many many iterations, especially for a large number. So:
function isPrime(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
As you can see, for a 10-digit prime, the running time is very much reduced:
function isPrimeSqrt(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
function isPrimeHalf(num) {
var max = Math.floor(num / 2);
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
let now = Date.now();
const pHalf = isPrimeHalf(1010189899);
console.log("Using 'Half' took:", Date.now() - now, "ms. Is prime:", pHalf);
now = Date.now()
const pSqrt = isPrimeSqrt(1010189899);
console.log("Using 'Sqrt' took:", Date.now() - now, "ms. Is prime:", pSqrt);
Got it!
Simply change this line:
for (var j = min; j <= max; j++) {
to this:
for (var j = parseInt(min); j <= parseInt(max); j++) {
Get familiar with Debugger Tools (F12 in most browsers). There you can pause execution in certain lines and check value and type of variables. If you do it, there you'll see than min = "5", insted of min = 5. That's why 5-49 doesn't work, beacuse "5" is smaller than "49" (beacuse it's first digit is lower), so it doesn't loop at all.

Scoring system for a quiz

How do I get the scoring system to work right?
It adds +1 if it's correct, but + an even bigger number if it's wrong...I just want it to add +1 to both.
It should post only +1 for wrong...
HTML
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question1' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question2' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question3' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question4' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question5' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question6' id='question6'>
</h5>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question7' id='question7'>
</div>
<button id='button' type='button' onclick='answer()'>Do you even anime?</button>
</form>
<span class='correct'>
<label for='score'>CORRECT</label>
<input type='text' id='score'>
</span>
<span class='wrong'>
<label for='wrong'>WRONG</label>
<input type='text' id='wrong'>
</span>
JavaScript:
var quizArray = [
{ answer: 'ashente' },
{ answer: 'green' },
{ answer: 'yes' },
{ answer: 'love' },
{ answer: 'both' },
{ answer: 'chopper' },
{ answer: 'heavens' }
]
function answer() {
var correct = 0;
var wrong = 0;
for (i = 0; i < quizArray.length; i++) {
var question1 = document.getElementById('question1').value;
if (question1 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question3 = document.getElementById('question3').value;
for (i = 0; i < quizArray.length; i++) {
if (question3 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question4 = document.getElementById('question4').value;
for (i = 0; i < quizArray.length; i++) {
if (question4 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question5 = document.getElementById('question5').value;
for (i = 0; i < quizArray.length; i++) {
if (question5 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question6 = document.getElementById('question6').value;
for (i = 0; i < quizArray.length; i++) {
if (question6 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question7 = document.getElementById('question7').value;
for (i = 0; i < quizArray.length; i++) {
if (question7 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
Here it is. You have several problems. Check teh code and feel free to ask anything:
var quizArray = [{
answer: 'ashente'
}, {
answer: 'green'
}, {
answer: 'yes'
}, {
answer: 'love'
}, {
answer: 'both'
}, {
answer: 'chopper'
}, {
answer: 'heavens'
}]
function answer() {
var correct = 0;
var wrong = 0;
var questions = document.querySelectorAll(".question");
for (i = 0; i < quizArray.length; i++) {
if (questions[i].value.toLowerCase() == quizArray[i].answer.toLowerCase()) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
(function(){
document.getElementById("button").addEventListener("click", answer);
})();
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question' id='question6'>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question' id='question7'>
</div>
<input id='button' type='submit' value="Do you even anime?">
<span class='correct'><label for='score'>CORRECT</label><input type='text' id='score'></span>
<span class='wrong'><label for='wrong'>WRONG</label><input type='text' id='wrong'></span>
I will calrify some points anyway. As you could see, the main difference is the size of the js. You had teh same piece of code for each question, when you are in a situation like this, you should use a function or a loop. This is part of the DRY concept. So taking all the questions in an array and iterate over them is easier than create a piece of code for each one.
I added the function toLowerCase because is annoying failing answers only if you missed that detail. Using this function is not necessary, it's up to you.
In the HTML part I must remark that if you have a button that sends a form you should create an input which type is submit. HTML button is not properly for submitting a form. It can do the job, but it is not the correct way.
You use inputs to show the score, but, instead it will be better to use plain text. Again, it's not bad but it's handier.
The issue is related to how the incrementing is implemented in the for-loops. Let's take the first loop as an example:
You are trying to assess whether or not question 1 has been answered correctly by comparing the users answer with every possible answer in the quizArray element. With 7 questions we should have 7 iterations of the loop. In each iteration, you check if the answer for question 1 is correct and increment the correct variable accordingly. Otherwise you increment the wrong variable. So for 7 iterations of the for-loop you are incrementing the wrong variable at least 6 times.
Instead of trying to increment the correct and wrong variables in each iteration, you can use a flag to determine if the question was answered correctly, and then increment the variables after the loop. For example:
var correct = 0;
var wrong = 0;
var question1 = document.getElementById('question1').value;
var answerCorrect = false;
for (i = 0; i < quizArray.length; i++) {
if (question1 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
answerCorrect = false;
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}

How to make Ulam number sequence in javascript?

I can't figure this problem out, I already checked my code but I don't know what the problem is.
This is the question: A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows.
if n is 1, it will stop.
if n is even, the next number is n/2.
if n is odd, the next number is 3 * n + 1.
continue with the process until reaching 1.
here some examples for the first few integers.
2->1
3->10->5->16->8->4->2->1
4->2->1
6->3->10->5->16->8->4->2->1
7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
Sample Run:
Enter Positive Integer: 5
The ulam Number Sequence is : 5->16->8->4->2->1
this is my code...
<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>
function isOdd(num) {
var odd = true;
for (var i = 0; i <= num; i++) {
if (num % i == 0) {
odd = false;
break;
}
}
return odd;
}
function isEven(num) {
var even = true;
for (var i = 0; i <= num; i++) {
if (num % i == 1) {
even = false;
break;
}
}
return even;
}
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];
for(var i = 0; i <= n; i++){
if(isOdd(i)){
result1[result1.length] = i /2;
}
if(isEven(i)){
result1[result1.length] = 3 * i + 1;
}
if(isOdd(result1)){
result1[result1.length] = result1 / 2;
}
if(isEven(result1)){
result1[result1.length] = 3 * result1 +1;
}
//result1[result1.length] = i * 3 + 1;
document.getElementById("info").innerHTML = result1.join("->");
}
}
function Reset(){
document.getElementById("info").innerHTML = "";
document.getElementById("num").value = "" ;
}
</script>
</body>
</html>
Maybe this is a solution for you (and a little hint):
function process() {
var n = parseInt(document.getElementById('num').value),
result = [n];
if (isFinite(n) && n && n === Math.abs(n)) {
while (n !== 1) {
// basically this is all to do.
n = n % 2 ? 3 * n + 1 : n / 2;
result.push(n);
}
document.getElementById("info").innerHTML = result.join(' > ');
} else {
document.getElementById("info").innerHTML = 'Does not compute!';
}
}
function reset() {
document.getElementById('info').innerHTML = '';
document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="reset()">Reset</button>
</form>
<p id="info"></p>

Javascript Product Search (working, but need to filter by search term)

I have a little product search code that I've been working on for a while. It works great, although a bit backwards.
The more keywords I type in, ideally, the less products will show up (because it narrows down the results). But as is stands, the more keywords I type in my search system, the MORE products are displayed, because it looks for any product with any of the keywords.
I want to change the script so that it only shows results if they include ALL the searched for keywords, not ANY of them...
Sorry for the long-winded explanation.
Here's the meat and potatoes (jsfiddle):
http://jsfiddle.net/yk0Lhneg/
HTML:
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
JAVASCRIPT:
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].style.display = "block";
}
}
}
}
}
So, when you search "mac pc" the only result that should be displayed is the hybrid, because it has both of those keywords. Not all 3 products.
Thank you in advance!
I changed a little bit your code to adjust it better to my solution. I hope you don't mind. You loop first over the terms, and then through the list of products, I do it the other way around.
How this solution works:
Traverse the list of products, for each product:
Create a counter and set it to 0.
Traverse the list of search terms, for each.
If the word is found in the product's name, add 1 to the counter.
If the counter has the same value as the list length, display the product (matched all words)
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
// I moved this loop outside
var nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
// set a counter to zero
var num = 0;
// I moved this loop inside
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
// only run the search if the text input is not empty (to avoid a blank)
if (str_needle !== "") {
// if the term is found, add 1 to the counter
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
num++;
}
// display only if all the terms where found
if (num == searchStrings.length) {
nameDivs[j].style.display = "block";
}
}
}
}
}
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
You can also see it on this version of your JSFiddle: http://jsfiddle.net/yk0Lhneg/1/

Categories