Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
ok so i have an input and am trying to make it so that when a specific name is inputted, it gives an alert and e.off()'s. I do not know why this code wont work. the code is in a function but that is ok, I am just having problems here Thank You. the html input does have an id of #nameInput so we are ok there too.
var name = $('#nameInput').val();
var names = ["john","jon","johnn"];
var a = names.indexOf("john","jon","johnn") > -1;
if (name == a) {
alert('That is the Bosses name silly!');
e.off();
}
The .indexOf() function is not a jQuery thing; it's part of (modern) standard JavaScript. It takes one argument and one optional argument. The first is the thing to search for, and the second optional argument is the starting position for the search (default being index 0).
The function returns a number, as your code seems to expect. However, you then compare the name in the input field to the true/false returned from the comparison following your (incorrect) call to .indexOf(), so it's not surprising that it doesn't do what you expect.
var name = $('#nameInput').val();
var names = ["john","jon","johnn"];
var bad_name = false;
for(var k in names) {
var this_name = names[k];
if( name.indexOf(this_name) > -1 ) {
bad_name = true;
break;
}
}
if(bad_name) {
alert('That is the Bosses name silly!');
e.off();
}
.indexOf was used incorrectly. The object it is called on should be the name string, not the list of names, and it only takes one parameter, so you have to do multiple checks.
Also, the a value would have been a boolean, so you directly check its value, not compare it to name
If all this is in a function, consider having another function outside of it so that you can reuse it later if needed. You need to iterate through the array of names matching your string against the array's items. There are many many ways to do it, but here's an easy one.
function isName(inputName, namesArray) {
var nameFound = false; // Returns false if there's no match
namesArray.forEach(function(name) { // For each name in namesArray
if (inputName === name) {
nameFound = true;
}
});
return nameFound;
}
console.log(isName('john', ['john', 'jon', 'johnn']));
console.log(isName('nobody', ['john', 'jon', 'johnn']));
// You can then have your if statement
if(isName(name, names)) {
alert('That is the Bosses name silly!');
e.off();
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I'm currently studying Javascript and the teacher asked us to create a program that allows users to create, edit and delete hotels using object arrays.
I managed to created the showHotels() function without any issue but I'm having troubles deleting a specific hotel from the created array as when I use the splice() method it deletes the object selected but also all the following ones.
The user will have to enter the name of the hotel in order to delete it, we therefore do not know the index of the object.
I am only allowed to use Visual Studio Code and nothing else to write my code.
import { Hotel } from "./hotels.js"
document.getElementById('createHotel').addEventListener('click', createHotel)
document.getElementById('deleteHotel').addEventListener('click', deleteHotel)
document.getElementById('showHotel').addEventListener('click', showHotel)
document.getElementById('editHotel').addEventListener('click', editHotel)
let myHotelArray = []
function createHotel() {
const hotelName = prompt(`Please enter the name of hotel:`, `W Hotel`)
const numberOfRooms = prompt(`Please enter the number of rooms:`, `68`)
const numberOfFloors = prompt(`Please enter the number of floors:`, `12`)
const totalArea = prompt('Please enter the total area of the hotel:', `250`)
myHotelArray.push(new Hotel(hotelName, numberOfRooms, numberOfFloors, totalArea))
}
function showHotel() {
let hotelsFormated = []
for (let i = 0; i < myHotelArray.length; i++) {
hotelsFormated.push(`${myHotelArray[i].toString()} <br><br>`);
}
document.getElementById('hotels').innerHTML = hotelsFormated.join('')
console.log(myHotelArray)
}
function deleteHotel() {
const selectHotel = prompt(`Please enter the name of the hotel you'd like to delete:`)
const hotelIndex = myHotelArray.findIndex(i => i.hotelName === selectHotel)
if (hotelIndex >= 0) {
myHotelArray.splice(hotelIndex)
}
else {
alert("This hotel couldn't be found. Please try again")
}
function editHotel() {
}
}
As mention in mdn Array.splice can receive 2 arguments:
start: Zero-based index at which to start changing the array (dont
know what the zero-based mean but use the start argument as any
natural Number)
deleteCount: An integer indicating the number of elements in the
array to remove from start.
I think adding deleteCount in your statment like this myHotelArray.splice(hotelIndex, 1) will solve it.
The splice method will remove from the list and return all the items from hotelIndex to hotelIndex+deletCount.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm making basic search on my website. When you type into the search it automatically compares the input against every element-id in the document. When it finds a match it scrolls to the matched element. As of now the search works only when you input the exact id (excluding case-sensitivity and spaces).
Here is my JQuery code:
$('#search-box').focus(function() {
$('#search-box').keyup(function () {
var x = $('#search-box').val().replace(/\s+/g, '').toLowerCase();
if ($("#" + x).length !== 0) {
navbarHeight = $('#fixed-navbar').height();
$('html, body').animate({scrollTop:$('#'+x).position().top - window.navbarHeight}, 500);
}
});
});
I think, I've tried everything starting from .match() to using plugins like List.js.
Is there a way to compare inputed text to id's and output the first matching one? Tolerance modifier would be neat but not required.
My solution:
// Searches automatically for first matching id
var idArray = $("div[id^='x-']") // find spans with ID attribute
.map(function() { return this.id; })// convert to set of IDs
.get(); // convert to instance of Array (optional)
navbarHeight = $('#fixed-navbar').height();
console.log(idArray);
$('#search-box').keyup(function () {
for (var i=0; i<idArray.length; i++) {
var input = $('#search-box').val().replace(/\s+/g, '').toLowerCase();
matched = idArray[i].match(new RegExp(input));
if (matched !== null) {
$('html, body').animate({scrollTop:$('#'+ idArray[i]).position().top - window.navbarHeight});
console.log('Matched part: ' + matched);
break;
};
if (matched == undefined) {
matched = [];
matched.length = 0;
};
};
});
Working JSFiddle.
(thx for help guys /s)
Final thoughts:
I didn't add the tolerance variable but it's easy enough (compared to this IMO).
Also, I may add so that it stats to search only from the beginning of the id (because people usually start typing the beginning of the word) but then the "search anywhere in the name" functionality won't work.
Edit: Finally managed to make it work the way I asked to. Code almost rewritten and updated.
So I want to create a function that if, if a question is answered wrong, it stores the wrong answer into a new object? So that I can list all of the wrong answers at the end?
var answerList = [{question:1, answer:1},{question:2, answer:2},]
var listofWrongAnswers = [];
if (answerSelected != answerlist[1].answer) {
/* create a new object
put answerlist[1].question and answerlist[i].answer in new object and push to
array ListofWrongAnswers */
}
I dont get how you can randomly name variables? if that's even possible.
Couldn't you simply create a new object based on the current question?
Something like this should work:
if (answerSelected != answerlist[1].answer) {
listofWrongAnswers.push({question: answerlist[1].question, answer: answerlist[1].answer});
}
However, you should look to make that index a parameter:
function addToWrongAnswers(answerSelected, idx) {
if (answerSelected != answerlist[idx].answer) {
listofWrongAnswers.push({question: answerlist[idx].question, answer: answerlist[idx].answer});
}
}
I assume you want something like this:
function getQuestion(number){
for(var i = 0; i < answerList.length; i++){
if(answerList[i].question === number){
return answerList[i];
}
}
}
function checkAnswer(questionNumber, answer){
var question = getQuestion(questionNumber);
if(answer !== question.answer){
listofWrongAnswers[question];
}
}
However, I'm also assuming you'll start with Question 1 and increment the number, so it would be even simpler if you just selected the question using an array index, rather than iterating through it. So this might be better:
var answerList = [{question:1, answer:1}, {question:2, answer:2}];
var listofWrongAnswers = [];
function checkAnswer(questionNumber, answer){
var question = answerList[questionNumber - 1];
if(answer !== question.answer){
listofWrongAnswers[question];
}
}
If you want to clone that question object and push it into that array, you can use
listofWrongAnswer.push({question: answerlist[1].question, answer: answerlist[1].answer});
But with this code you won't can use == operator to compare question objects existing at those arrays
listofWrongAnswer[1] == answerlist[1] // It's false
But if you don't want such a behavior you can store only references to question objects in the wrong answer list:
listofWrongAnswer.push(answerlist[1]);
With this code you can compare question objects with == operator
listofWrongAnswer[1] == answerlist[1] // It's true
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Working on a flight booking website. Have a json file which contains the airport codes, city name and country name.
[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]
Now if my iata airport code matches to UTK i want to return the name.
Use filter() to find the object within the Array by its iata:
var arr = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];
function findByCode(arr, iata){
var filtered = arr.filter(function(e){return e.iata = iata});
return (filtered.length == 1) ? filtered[0]:undefined;
}
console.log(findByCode(arr,"UTK").name);
JS Fiddle: http://jsfiddle.net/dE9nP/
$string = '[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]';
$data = json_decode($string);
echo count($data);
for($i=0;$i<count($data);$i++){
if($data[$i]->iata == 'UTK') echo $data[$i]->name;
}
you can use file_get_contents if the data in a file instead of $string;
This is basic searching! You need to loop over the array, and check each item for the matching code, then return the result. Here is a function:
function findAirport(myArray, iata){
for(var i = 0; i < myArray.length; i++){
var item = myArray[i];
if(item["iata"] === iata){
return item;
}
}
return null;
}
You can use that function like so:
var airports = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];
var match = findAirport(airports, "UTK");
if(match){
console.log("name = " + match.name);
}
Just to highlight my preference to using simple for loops over other functions such as filter, here is a performance test comparing my answer to the other one that uses filter. I know it's meaningless in most real use cases, but I wanted to keep a reference to the jsperf link :)
NOTE: This answer was provided before the question tags were edited. At the time of posting this question was asking for a javascript solution
I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.