text search in javascript? - javascript

I have a page with more than 200 links with this kind of formatting.
<h1>
Somelink
some text that explain the meaning of the link.
</h1>
Now, to make it bit easy to search through this link, i have put a search box.
My requirement is to search through all this tag and find the links that are relevant to
the search box and hiding rest of the link.
How to do it in javascript ? ( i know basic javascript/jquery stuff but How to do full text search ? ) I do not required sorting according to relevant, just filter and show hide is good enough.

You can enumerate all h1 tags get inner html and do indexOf , or you can use jQuery it has a custom made contains functionality, which returns the elements having given text.
Here is an example copied from jQuery docs
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
</body>
</html>

Hopefully you find this useful. It probably is not the elegant or most efficient but it will let you enter multiple search terms and gives partial matches (which may or may not be wanted). The way I have made it when you click the search button it will hide all other elements except ones matching either of your search terms but you can modify this to do whatever you want with the elements in the results Array. I don't recommend using this exactly but hopefully it will give you a point of reference on how you may want to implement your own (if you choose to go with a solution other than the quicksearch).
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type='text/javascript' language='javascript' >
$(document).ready(function() {
var links = new Array();
$("h1").each(function(index, element) {
links.push({
text: $(this).text(),
element: element
});
});
$("#searchButton").click(function() {
var query = $("#searchBox").val();
var queryTerms = query.split(' ');
var results = new Array();
for(var i = 0; i < queryTerms.length; i++) {
for(var j = 0; j < links.length; j++) {
if (links[j].text.indexOf(queryTerms[i]) > -1) {
results.push(links[j].element);
}
}
}
$("h1").each(function(index, element) {
this.style.display = 'none';
});
for(var i = 0; i < results.length; i++) {
results[i].style.display = 'block';
}
});
});
</script>
</head>
<body>
<p>
<input id="searchBox" type="text" />
<input type="button" id="searchButton" value="Search" />
</p>
<h1>
Somelink1
asdf
</h1>
<h1>
Somelink2
ssss
</h1>
<h1>
Somelink3
3333
</h1>
<h1>
Somelink4
232323
</h1>
<h1>
Somelink5
fffff
</h1>
</body>
</html>

I found one.
http://github.com/riklomas/quicksearch
which uses regex for search.

Related

I'm trying to append an image from a javascript object Array onto my html page

So I was able to create a movie class array with 4 constructors, and a for loop with 3 iterations that represent three different movies. On the html page this allows the user to open a dropdown selection and pick one of the three movies. After hitting the submit button I want to display all the info for all the movie they selected including its image which is the difficult part. Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="Script.js"></script>
</head>
<body>
<form >
<select>
</select>
<button onclick="showDetail()">Submit</button>
</form>
<p></p>
</body>
</html>
class movie {
name;
price;
image;
genre;
constructor(x,y,z,a){
this.name = x;
this.price = y;
this.image = z;
this.genre = a;
}
}
let movies =[];
movies[0]= new movie("Deadpool", "$6.95","Image/Deadpool.jpg", "Superhero, Action");
movies[1]= new movie("Titanic", "$4.95", "" , "Romance, Drama");
movies[2]= new movie("Spiderman 3", "$6.95","", "Superhero, Action");
$(document).ready(function() { console.log( "ready!");
for (var i = 0; i < 3; i++){
movies[0].image= "Image/Deadpool.jpg";
movies[1].image= "Image/Titanic.jpg";
movies[2].image= "Image/Spiderman.jpg";
$("select").append(`<option>${movies[i].name}</option>`); console.log(i) }});
function showDetail(){
for (var i = 0; i < 3; i++){
$("p").append(`${movies[i].price},${movies[i].genre}, ${movies[i].image}`);
}
}
You can append HTML using .append() but I would not recommend appending it to a paragraph tag, and using the paragraph selector, try doing this:
<div id="details"> </div>
Add the above instead of the paragraph tag and then in jquery you could so something like:
$('#details').append(`<h1> ${movies[i].price} </h1> <p> ${movies[i].genre} </p> <img src="${movies[i].image}" alt="movie" />

Animating a walk cycle using only Javascript and HTML

I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.

Load Function to HTML//Generate Random Words

I'm super stuck. I'm creating a hangman game for a class and I cannot get the words to generate and show in my HTML. We're required to have them show as underscores but I cannot get them to show in the HTML either. I've been able to get it to show in the console but not in my HTML.Any help would be appreciated or any assistance in troubleshooting.
please see the code.
//horror movie titles selected to guess
var movieTitles = [
"halloween",
"suspiria",
"audition",
"hereditary",
"the beyond",
"the evil dead",
"the blair witch project"
];
//letters already guessed
var guessedLetters = [];
var numOfLetters = [];
//randomly assigned variable
var movieToGuess = null;
//attempts left
var livesLeft = 8;
//games won
var wins = 0;
//games lost
var losses = 0;
window.onload = function() {
updateMovieToGuess();
};
var updateMovieToGuess = function() {
for (var i = 0; i < numOfLetters.length; i++){
numOfLetters[i] = "_".join(" ");
}
var movieToGuess = movieTitles[Math.floor(Math.random() * movieTitles.length)];
document.getElementById("movie-title").innerHTML = movieToGuess;
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="javascript/games.js"></script>
<link href="https://fonts.googleapis.com/css?family=IM+Fell+Double+Pica+SC" rel="stylesheet"> </head>
<body>
<p>Press any key to get started<span id='any-key'> </span> </p>
<p>Movie Title:<span id="movie-title"> </span> </p>
<p>Letters Guessed: <span id='letters'> </span> </p>
<p>Lives Remaining:<span id='lives-left'> </span> </p>
<p>Movies You've Survived:<span id='wins'> </span> </p>
<p>Movies You Died In:<span id='lost'> </span> </p>
<footer> </footer>
</body>
</html>
Two problems:
querySelector is looking for <movie-title> instead of <span id="movie-title">. To fix it, either use getElementById instead of querySelector, or change movie-title to #movie-title.
As Mark Meyer pointed out in a comment, you're using movieToGuess before you set it.
EDIT: I see you edited your question and its code after I answered it. You fixed problem #2 but not #1. Worse, you introduced a new problem: you now add the call to updateMovieToGuess via window.onload inside of updateMovieToGuess instead of at top level, so it never gets called (essentially, you've created a chicken-and-egg problem).

Javascript display all (elements, tags) from method elementsbyTagName

Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>

Retrieve text from search box

I'm building a program that allows me to search a document to see how many times a word appears within that document. I would like to choose which word to search by entering the desired word into a search box that I've built. Currently, If I hard code the word that I'm searching for, it'll search the document and tell me how times it appears. If I try to use the search box to enter a word, I always get a result of 0. I need a way to retrieve the word entered from the search box and use that word as the word that I want to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WordBubble</title>
<link rel="stylesheet" type="text/css" href="wordbubble.css">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
</head>
<body>
<div id="search">
Search Word: <input type="search" name="Wordsearch" size="35">
<button type="submit" class ="searchme">Search</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".searchme").click(function(){
var myWord = $ (this).text();
findDuplicates();
});
});
// ajax call to get comments document
function findDuplicates (myWord) {
$.get( "comm.txt", function( text ) {
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = []
for (var i=0; i<sortedWords.length-1; i++) {
if (myWord == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
$( "p" ).html(duplicateWords.length);
});
}
</script>
<p></p>
</body>
</html>
In your click-handler you retrieve the searchstring from the button instead from the input.
$(document).ready(function(){
$(".searchme").click(function(){
// get the word from the input
var myWord = $('input').val();
findDuplicates(myWord);
});
});

Categories