I'm making a function to find the all movies made by the actor i search for, the movies are in a js file like so:
var filmlist = [
{"Title":"Killer's Kiss", "Actors":"Frank Silvera, Jamie Smith, Irene Kane, Jerry Jarrett"}
];
var a = document.getElementById("film");
function findActors() {
var x = document.getElementById("actor").value;
var y = document.getElementById("actorfilm");
a.innerHTML = "Movies with this actor: "
for (var i=0; i<filmlist.length; i++) {
if (x.indexOf(filmlist[i].Actors) !== -1) {
y.innerHTML = (filmlist[i].Title + "<br/>")
}
}
}
<textarea rows="2" cols="50" id="actor" placeholder="write actor name, and press the button"></textarea>
<button onclick="findActor()">ActorButton</button>
<p id="film"></p>
<p id="actorfilm"></p>
For some reason it wont show the actors, but it shows the first a.innerhtml
Im very new to javascript so any help is appreciated.
You are almost there, just that your if condition needs to be reversed.
if (filmlist[i].Actors.indexOf(x) )
You were checking the superset of actors within the value you have input, rather than doing it the other way round.
You can make it more precise by doing
var filteredFilms = filmlist.filter( s => s.Actors.indexOf(x) != -1 );
var output = filteredFilms.map( s => s.Title ).join( "<br/>" );
Demo
var filmlist = [{
"Title": "Killer's Kiss",
"Actors": "Frank Silvera, Jamie Smith, Irene Kane, Jerry Jarrett"
}];
var a = document.getElementById("film");
function findActors() {
var x = document.getElementById("actor").value;
var y = document.getElementById("actorfilm");
a.innerHTML = "Movies with this actor: "
var filteredFilms = filmlist.filter(s => s.Actors.indexOf(x) != -1);
y.innerHTML = filteredFilms.map(s => s.Title).join("<br/>");
}
<!-- find actor function -->
<textarea rows="2" cols="50" id="actor" placeholder="write
actor name, and press the button">Frank Silvera</textarea>
<button onclick="findActors()">ActorButton</button>
<p id="film"></p>
<p id="actorfilm"></p>
You are currently overwriting y.innerHTML with the last movie title. To append, to the innerHTML use:
y.innerHTML += (filmlist[i].Title + "<br/>")
There is an issue with your indexOf, mentioned in another answer and can be fixed with
if (filmlist[i].Actors.indexOf(x)) {
Lastly, your HTML is incorrectly referencing the js function and should instead be:
<button onclick="findActors()">ActorButton</button>
Related
i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');
I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.
I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .
This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>
This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']
#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}
I'm currently working on a digital assistant website which is based around JavaScript and jQuery. The user can type in questions or tell the assistant things into the textbox and the assistant will respond with something relevant to the input. What I am planning to implement is to check if the textbox contains a number (intager) and if it does some sort of function will run. The concept sounds fairly simple and but I am having trouble. I have been searching around for a bit but I can't seem to find anything which will work with my code.
I will add my JavaScript and the nessacary parts of the HTML. But I am warning you, the code is messy.
JavaScript:
// JavaScript Document
function submitted() {
var srch = document.getElementById("srch");
command();
getPlaceHolder();
srch.value = "";
}
function searchKeyPress(e) {
e = e || window.event;
if (e.keyCode == 13) {
//document.getElementById('btn').click();
submitted();
}
}
function goBtn() {
submitted();
}
function refreshBtn() {
getWelcome();
}
function stClock() {
window.setTimeout("stClock()", 1000);
today = new Date();
self.status = today.toString();
}
function getWelcome() {
var ar = new Array(20)
ar[0] = "What's on your mind?";
ar[1] = "How can I help?";
ar[2] = "Anything you need help with?";
ar[3] = "Ask me anything";
ar[4] = "What can I help you with?";
ar[5] = "What would you like me to do?";
ar[6] = "What can I do for you?";
ar[7] = "Need help with anything?";
ar[8] = "Need someone to talk to?";
ar[9] = "I'm here to help";
ar[10] = "Anything you need to know?";
ar[11] = "How else can I help?";
ar[12] = "What can I do now?";
ar[13] = "Need anything?";
ar[14] = "Any problems you need solving?";
ar[15] = "Hello, how do you do?";
ar[16] = "Hi there";
ar[17] = "Hi, I'm aurum";
ar[18] = "Hello there";
ar[19] = "How do you do?";
var now = new Date();
var sec = now.getSeconds();
document.getElementById('output').innerHTML = ar[sec % 20];
}
function getPlaceHolder() {
var ar = new Array(20)
ar[0] = "What's on your mind?";
ar[1] = "How can I help?";
ar[2] = "Anything you need help with?";
ar[3] = "Ask me anything";
ar[4] = "What can I help you with?";
ar[5] = "What would you like me to do?";
ar[6] = "What can I do for you?";
ar[7] = "Need help with anything?";
ar[8] = "Need someone to talk to?";
ar[9] = "I'm here to help";
ar[10] = "Anything you need to know?";
ar[11] = "How else can I help?";
ar[12] = "What can I do now?";
ar[13] = "Need anything?";
ar[14] = "Any problems you need solving?";
ar[15] = "Hello, how do you do?";
ar[16] = "Hi there";
ar[17] = "Hi, I'm aurum";
ar[18] = "Hello there";
ar[19] = "How do you do?";
var now = new Date();
var sec = now.getSeconds();
document.getElementsByName('srch')[0].placeholder=ar[sec % 20];
}
function command() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
var t = srch;
var outputElement = document.getElementById('output');
if (srch == '') {
outputElement.innerHTML = "How can I help you, if you don't say anything?";
}
else if (srch.indexOf('about') != -1) {
outputElement.innerHTML = "Hello, I'm Aurum. I was designed by Omar Latreche to help people answer their questions. However, I also like to talk to people aswell as answer their questions.";
}
else if (srch.indexOf('time') != -1) {
outputElement.innerHTML = 'The current time according to your computer is' + ShowTime(new Date());
}
else {
if (confirm("I am sorry but for some reason I don't understand. You could either repeat that or would you like to search Google for that instead?") == true) {
window.open('https://www.google.co.uk/#q=' + srch, '_blank');
}
else { /* Nothing */ }
}
}
//Show time in 12hour format
var ShowTime = (function() {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function(dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
};
})();
And the HTML:
<!DOCTYPE html>
<html>
<body onload="getWelcome(); getPlaceHolder();">
<div class="output" id="output">
An error has occoured. Please make sure you have JavaScript enabled in your browser.
</div>
<div class="cont">
<div class="ui-widget">
<div class="search-cont">
<input class="search-field" id="srch" name="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false"> <input class="refresh" onclick="refreshBtn()" title="Refresh the conversation" type="button"> <input class="go" onclick="goBtn()" type="button">
</div>
</div><br>
</div>
</body>
</html>
I really appreciate any help provided. Thanks, Omar.
PS. I apologies for the long paragraph but that is the only way I could think to explain what I need.
PPS. If you need any more information on my project just incase, the URL is http://omarlatreche.tk/aurum/
This is the function I came up with to check for number:
function checkNum() {
text = document.getElementById('srch').value;
valArr = document.getElementById('srch').value.split(' ');
for (i = 0; i < valArr.length; i++) {
if (isNaN(valArr[i])==false) {
alert("Number found");
}
}
}
Here is the JSFiddle demo
I called the function in the goBtn() function.
can you explain this line?
document.getElementById('output').innerHTML = [0].innerHTML=ar[sec % 20];
shouldn't it be
document.getElementById('output').innerHTML = ar[sec % 20];
I am trying to allow the user to enter 1 letter in a text box, and then the letters gets put into 1 of 2 boxes. This is for a hangman game, so it is going to divide the letters based on whether or not it is in the word. Here's my code. Hopefully someone can help me. I'm new to javascript! I've done a ton of googling, but to little avail.
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord()
{
var textarea = document.getElementById('textBox').value;
for (var x = 0; x<wordLength; x++)
{
if (textarea === wordForGuess.indexOf(x))
{
document.getElementById('correctLetters').value = textarea;
}
else
{
document.getElementById('incorrectLetters').value = textarea;
}
}
}
As well as the HTML for my textbox
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' onkeyUp="writeWord()"/>
<div id = 'correctLetters'>
</div>
<div id = 'incorrectLetters'>
</div>
I think you have a few mistakes, including iterating over your characters in your chosen word and using the index of that iteration instead of just checking the value from the input box. I also think you should reset the value on each keyup. I also moved your onkeyup event out of the HTML into JavaScript, I think maybe in your case the JavaScript hadn't loaded yet but it's hard to tell from your example.
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' />
<br/>
Correct:
<div id = 'correctLetters'>
</div>
<br/>
Incorrect
<div id = 'incorrectLetters'>
</div>
Here's the JavaScript with some fixes:
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord() {
var input, textarea;
input = document.getElementById('textBox')
textarea = input.value;
input.value = "";
console.log("writing word", textarea);
if (wordForGuess.indexOf(textarea) !== -1) {
document.getElementById('correctLetters').innerText += textarea;
} else {
document.getElementById('incorrectLetters').innerText += textarea;
}
}
document.getElementById("textBox").onkeyup = writeWord;
Here's a jsfiddle with this code.