I have been trying to make a very simple search engine for a school project, but I can't figure out how to compare the user input I receive (a string from an input-textbox) to data I have in an array (A NodeList object with a bunch of names).
I will elaborate a little bit on exactly what I want to achieve: I have a HTML page which contains a input form and a bunch of movie titles (in format) and I want to compare what the user types in the input form to the movie titles that are on the page. If the user input matches one of the movie titles I want that movies' highlighted, and if the input doesn't match any movies, I just want an alert box to pop up saying that the input didn't match any movies.
I have been trying to do it like this:
var All_Titles = document.getElementsByTagName("h3");
var User_Input = document.forms["search_form"];
function InputValidation() {
var x = document.forms["search_form"]["input_box"].value;
if (x == "" || x == null) {
alert("You haven't entered anything");
} else {
Search();
}
}
function Search() {
if (User_Input == All_Titles) {
document.writeln("It worked!");
} else {
alert("No matched movies");
}
}
As you can see, I first capture the user input in a var called "User_Input", and I do the same with the movie titles.
Then, I check if the user has actually any text into the search form; if they didn't, they receive an error message and if they did, I run the Search() function, which is defined below.
Here comes the tricky part: I don't really know how I can compare the user input to the 's that I have! I have tried it with an If-Statement as you can see, but that doesn't seem to work.
Can anyone assist me with this problem?
I prefer using jQuery witch allows to do the same with less coding.
using jQuery:
<script type="text/javascript">
function search() {
var flag = false;
movieName = $("#movieSearch").val();
$(".moviesList").children("h3").each(function(index) {
if (movieName === $(this).html()) {
$(this).css("background-color", "yellow");
flag = true;
} else {
$(this).css("background-color", "white");
}
});
if(flag == false) {
alert("no such movie was found");
}
}
</script>
same code but only JS (less readable and maintainable):
<script type="text/javascript">
function search() {
var flag = false;
movieName = document.getElementById("movieSearch").value;
movies = document.getElementsByTagName("h3");
for (var i = 0; i < movies.length; i++) {
if (movieName === movies[i].innerHTML) {
movies[i].style.backgroundColor = "yellow";
flag = true;
} else {
movies[i].style.backgroundColor = "white";
}
}
if(flag == false) {
alert("no such movie was found");
}
}
</script>
HTML:
<div class="moviesList">
<h3>HHH</h3>
<h3>mmm</h3>
<h3>123</h3>
</div>
<input type="text" id="movieSearch" />
<button onclick="search()">Search By Name</button>
jQuery is a very common js library. use it by simply adding:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
You may try this example
var search = function() {
var movie = document.getElementById("movie").value;
if(!movie.replace(/\s+/g,'')) {//remove blank spaces
alert('Movie name required !');
return;
}
movie = movie.toUpperCase();
var list = document.getElementById('movieList');
list = list.getElementsByTagName('li');//movie title list
var i = list.length, html, flag = false, matches = [];
while(i --) {//walk through the list
html = list[i].innerHTML.toUpperCase();//get the movie in the li
if(-1 !== html.indexOf(movie)){//-1, string not found
flag = true;
matches.push(html);
}
}
if(!flag) {
alert('No match found !');
} else {
alert('Matched: ' + matches.join(', '));//show matching movies csv
}
};
<ul id="movieList">
<li>Star Wars</li>
<li>X-Men</li>
<li>MIB</li>
</ul>
<p>
Search <input type="text" id="movie"/><input type="button" onclick="search()" value="Search"/>
</p>
Use a loop to iterate through all the titles, comparing each with the user input
function Search() {
User_Input = User_Input.trim();
var i, len, title;
len = All_Titles.length;
for(i = 0; i < len; i++){
title = All_Titles[i].innerHTML.trim();
if(User_Input === title){
document.writeln("It worked!");
return;
}
}
if(i === len){
alert("No matched movies");
}
}
Here is my solution
function Search()
{
if (All_Titles.indexOf(User_Input)>-1)
{
alert("yes");
}
else
{
alert("No matched movies");
}
}
This solution may work for you.. try it
var arr = [];
for (var i = 0, ref = arr.length = All_Titles.length; i < ref; i++) {
arr[i] = All_Titles[i];
}
function Search()
{
if (arr.indexOf(User_Input)>-1)
{
alert("yes");
}
else
{
alert("not");
}
}
Array.prototype.indexOf = function(elt)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
Related
I am able to search and display the results that the user is typing on the keyup function. But now when the results show up inside my <div> tag, they are not clickable. Is there a way I can make them clickable and also allow the user to select multiple results from the live search results. This is what I tried so far.
HTML
<input type="text" id ="medication" name="medication" onkeyup="getsearch(this.value)"><br>
<div id="livesearch"></div>
JavaScript
function getsearch(val) {
results = [];
document.getElementById("livesearch").innerHTML = "";
if (val.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border = "0px";
return;
}
console.log(s);
console.log("val", val);
if (val.length > 2) {
for (var i = 0; i < s.length; i++) {
for (key in s[i]) {
if (s[i][key].indexOf(val) != -1) {
$("#livesearch").append(s[i][key]);
$("#livesearch").append("<br/>");
results.push(s[i]);
}
}
}
}
console.log(results);
};
There are some other thing I would do differently here, but as far as what you are looking to do this should work.
if(val.length>2) {
for (var i = 0; i < s.length; i++) {
for (key in s[i]) {
if (s[i][key].indexOf(val) != -1) {
var newDom = $('<div><\div>'); //create a DOM element to wrap each of the return text in.
newDom.text(s[i][key]);
$("#livesearch").append(newDom);
results.push(s[i]);
}
}
}
}
Then you can assign the click event to you dynamically created DOM this way.
$('#livesearch').on('click', 'div', myDoStuffFunc);
function myDoStuffFunc(){
// this is fired from the click event
}
I have the following function: http://jsfiddle.net/xznzyxyg/2/
Basically what it does it checks of the value of an input is equal to another value of another input in the same div.
Instead of the filtering I want it in an If function.
So that if true{ colour red}
The function I have now;
var inputs = $('#lol input');
var hoofdinput = document.getElementById('ad');
function Getred(i,el){
return inputs.not(this).filter(function() {
return hoofdinput.value === el.value;
}).length !== 0;
}).addClass('red');
What I want it in:
If (true){
// Colour red
}
else {
Alert('No duplicates');
}
Can somebody help me with this, I'm really frustrated with this one...
Thanks!!
EDIT: This is the solution, duplicates are coloured with red and others wich are not duplicate with green: http://jsfiddle.net/xznzyxyg/4/
is something like this what you are looking for?
var inputs = $('#lol input');
var hoofdinput = document.getElementById('ad');
for( var counter = 0; counter < inputs.length; counter++) {
if ( hoofdinput.value === inputs[counter].value )
inputs[counter].className += 'red';
else
alert('No duplicates');
}
var $inputs = $('div.myDiv input')
$inputs.each(function(i1, input1){
$inputs.slice(i1 + 1).each(function(i2, input2) {
if (input1.value == input2.value) $(input2).addClass('red');
});
});
Then if you need to alert that there were no matches
if ($('div.myDiv input.red').length == 0) alert('No duplicates');
I made array storing name of 5 different colors. So for example if string is "Bear is black and polar is white". Then I want to display that there are some color names in a string. But I can't do it as I am just a beginner & I know just basics of javascript. Now I am developing just small application that displays that there is color name in text or not. I thought that this will be a good way of learning. I am spinning my heads off since last 6 hours but now I gave up. Would anybody please help ? Pardon my indentation as I have wrote the code in hurry.
<script type="text/javascript">
function getNumber(){
var colors = ["black","blue","green","yellow","white"];
var getstring = document.getElementById("tobechecked");
var splitter = getstring.split(" ");
var i;
var j;
for(i=0;i<colors.length;i++){
for(j=0,j<splitter.length;j++){
if(splitter[j]==colors[i]){
alert("colors exists");
return true;
}
else
{
alert("colors don't exists");
return false;
}
}
}
}
</script>
<textarea rows="20" cols="50" id="tobechecked">
</textarea>
<button type="button" onclick="getNumber()"> Check !</button>
Try indexOf to check a string exists in another string
it'll return -1 if index not found
like this
var colors = ["black","blue","green","yellow","white"];
var getstring = document.getElementById("tobechecked");
for(var i=0;i<colors.length;i++)
{
if(getstring.value.indexOf(colors[i])>-1){
// exists
}
}
Use this:
function getNumber(){
var colors = ["black","blue","green","yellow","white"],
string = document.getElementById("tobechecked").innerText,
i,length = colors.length;
for( i=0; i < length; i++ ) {
if( string.indexOf( colors[i] ) !== -1 ) {
alert("colors exists");
return true;
}
}
alert("color doesn't exist");
return false;
}
Your code had a syntax error, plus you were returning from the function as soon as you did any test. You can return as soon as you find a color, but if you don't find one, you need to keep checking and only return failure at the end.
function getNumber() {
var colors = ["black", "blue", "green", "yellow", "white"];
var getstring = document.getElementById("tobechecked").value;
var splitter = getstring.split(" ");
var i, j;
for (i = 0; i < colors.length; i++) {
for (j = 0; j < splitter.length; j++) {
console.debug("Compare", splitter[j], colors[i]);
if (splitter[j] == colors[i]) {
alert("Color found");
return true;
}
}
}
alert("Color not found");
return false;
}
<textarea rows="20" cols="50" id="tobechecked">
</textarea>
<button type="button" onclick="getNumber()">Check !</button>
I have a javascript which appends a string like 222222222222222 to another field (which will either be blank or already have numbers like 222222222222222 33333333333333) with a click of a button. Actually it's 15 digit IMEI of the phone. User has the option of submitting a single IMEI or bulk IMEI. When more then one IMEI is added to the bulk field by pressing the button from myVar1, the new IMEI gets inserted below the previous IMEI in the bulk field(myVar2).
Currently, I am using the below script to do this and it's working perfectly fine. The problem is that it doesn't check for duplicates before appending.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}
I have modified the script now as below (updated to include the first response, thanks to Brian) to check for duplicates, but it's not working. Request experts to have a look into it.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
var flag = 0;
var wordsarr = myVar2.split("\r\n");
for(var i = 0; i < wordsarr.length; i++)
{
if(wordsarr[i].value == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}}
Here is the html of the page:
<html>
<body>
<input id="myVar1_value" type="text" maxlength="15" name="myVar1_value">
<input id="IMEI_ADD" class="button_gray" type="button" onclick="append_myVar1_to_myVar2()" value="Add this IMEI to bulk entry" name="IMEI_ADD">
<p id="imei_bulk_field" class="form-row notes">
<textarea id="myVar2_value" class="input-text" rows="2" cols="5" placeholder="If you have more than one IMEI, insert them here by pressing the button above." name="myVar2_value"></textarea>
</p>
</body>
</html>
for(var i = 0; i < (myVar2.split("\r\n")).length; i++)
{
//here is wrong
if(myVar2[i].value == myVar1)
{
flag = 1;
}
You should change to
var wordsarr = myVar2.split("\n");
for(var i = 0; i < worsarr.length; i++)
{
if(wordsarr[i] == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
Store splitted chunks ,and iterate over them:
var chunkArray = myVar2.split("\r\n");
for(var i = 0; i !== chunkArray.length; i++){
if(chunkArray[i] == myVar1){
flag = 1;
break;
}
}
var myVar2 = document.getElementById('myVar2_value').value;
Later...
if(myVar2[i].value == myVar1)
It looks like you are adding .value when you don't need to. Try:
if(myVar2[i] == myVar1)
This could be of assistance
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
you could change the if with:
haystack[i].value == needle
Hi I am trying to compare two arrays to each other and then hide a list element if any of the values match.
One array is tags that are attached to a list item and the other is user input.
I am having trouble as I seem to be able to cross reference one user input work and can't get multiple words against multiple tags.
The amount of user input words might change and the amount of tags might change. I have tried inArray but have had no luck. Any help would be much appreciated. See code below:
function query_searchvar() {
var searchquery=document.navsform.query.value.toLowerCase();
if (searchquery == '') {
alert("No Text Entered");
}
var snospace = searchquery.replace(/\s+/g, ',');
event.preventDefault();
var snospacearray = snospace.split(',');
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var searchtrue=-1;
for(var i = 0, len = searcharray.length; i < len; i++){
if(searcharray[i] == searchquery){
searchtrue = 0;
break;
}
}
if (searchtrue == 0) {
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
Okay so I've tried to implement the code below but have had no luck. It doesn't seem to check through both arrays.
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var snospace = searchquery.replace(/\s+/g, ' ');
event.preventDefault();
var snospacearray = snospace.split(' ');
alert(snospacearray[1]);
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
alert(searchtags);
var searcharray = searchtags.split(' ');
alert(searcharray[0]);
jQuery.each(snospacearray, function(key1,val1){
jQuery.each(searcharray,function(key2,val2){
if(val1 !== val2) {$(this).hide('slow');}
});
});
});
}
Working code:
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
if (found == true )
{
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
var snospace = searchquery.replace(/\s+/g, ',');
var snospacearray = snospace.split(',');
Note that you can split on regular expressions, so to the above would equal:
var queryarray = searchquery.split(/,|\s+/);
To find whether there is an item contained in both arrays, use the following code:
var found = searcharray.some(function(tag) {
return queryarray.indexOf(tag) > -1;
});
Although this will only work for ES5-compliant browsers :-) To support the others, use
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
In plain js, without jQuery.inArray:
var found = false;
outerloop: for (var i=0; i<searcharray.length; i++)
for (var j=0; j<queryarray.length; j++)
if (searcharray[i] == queryarray[j]) {
found = true;
break outerloop;
}
A little faster algorithm (only needed for really large arrays) would be to sort both arrays before running through them linear.
Here's psuedo code that should solve your problem.
get both arrays
for each item in array 1
for each element in array 2
check if its equal to current element in array 1
if its equal to then hide what you want
An example of this coude wise would be
jQuery.each(array1, function(key1,val1){
jQuery.each(array2,function(key2,val2){
if(val1 == val2) {$(your element to hide).hide();}
});
});
If there's anything you don't understand please ask :)