html form search in Array of objects [closed] - javascript

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 4 years ago.
Improve this question
I need to be able to search in an array of objects.
I have a HTML-for:
<form action="#" id="filters">
<label for="search">Search</label>
<input type="search" name="search" id="search"/>
</form>
<div id="searchresult"></div>
I have no idea how to begin, can someone help me?
Thanks in advance!

There are more than one ways to achieve what you are trying to do.
One way would be to attach an input event to the input field so that whenever there's a change in the input field value, you can get the input field value and then use filter method to filter the meals array based on the value of the input field. Finally, you can display the filtered results in the searchresult div.
const meals = [
{
id: 1,
title: 'Strawberry Salad with Poppy Seed Dressing',
img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
book: 1
},
{
id: 2,
title: 'Cashew Turkey Salad Sandwiches',
img: 'turkey-sandwich.jpg',
book: 2
}
];
const searchField = document.querySelector('#search');
const searchResultsContainer = document.querySelector('#searchresult');
searchField.addEventListener('input', (e) => {
// if input field is empty, clear the search results
if(e.target.value === '') {
searchResultsContainer.innerHTML = '';
return;
}
// filter the meals array
const searchResults = meals.filter(meal => {
return meal.title.toLowerCase().includes(e.target.value.toLowerCase());
});
// before displaying the search results, clear the search results div
searchResultsContainer.innerHTML = '';
// display the titles of the meal objects that include the text entered in input field
searchResults.forEach((element, index) => {
const p = document.createElement('p');
p.textContent = (index + 1) + '. ' + element.title;
searchResultsContainer.appendChild(p);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form action="#" id="filters">
<label for="search">Search</label>
<input type="search" name="search" id="search"/>
</form>
<div id="searchresult"></div>
</body>
</html>

Without revealing complete code and say, here you are, I will try to navigate you so you can come up with your own solution instead. follow roughly these steps:
listen to your search input = When you type on keyboard you want to
update search results. You can listen for onkeypress,
onkeydown or simple input change
other events inside the input
when key is pressed you need to check the new value inside input = You can do that by checking it's value property.
lastly, you want to get only objects from the list conforming to the
search value = there are sleek JS functions to filter out items in an
array or you can do it in standard for loop
Hope that gives you some idea about what to do. This might be a source of inspiration for you

Try using
array.filter(function(currentValue, index, arr), thisValue)

Related

Why does it come up with 'null' on my website when I try to print a user inputted word later on in the script? [closed]

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 3 years ago.
Improve this question
Here's my html so far:
<html>
<body>
<head>
<script>
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
var sentances = ['This new amazing product will be in every home by 2021','Buy this now- before we run out of stock!','Get this now, before everyone else will have one!'].sample()
var quotes = ['“This is amazing!"','"Buy it Now!"'].sample()
var titleback = ['"Nothing can beat','"How can you not love'].sample()
var title = document.getElementById("title")
function myfunction() {
document.getElementById("Sentances").innerHTML = sentances;
document.getElementById("Quotes").innerHTML = quotes;
document.getElementById("Titleback").innerHTML = titleback + title;
}
</script>
</head>
<h2>Auto Ad Generator</h2>
<p>Enter the title of your product:</p>
<form method="post" action=".">
<p><input name="name" id="title"></p>
<button type="button" id="button" onclick="myfunction()">Try it</button>
<p><input name="name2" type="reset"></p>
</form>
<p id="Sentances"></p>
<p id="Sentances2"></p>
<p id="Quotes"></p>
<p id="Titleback"></p>
</body>
</html>
Though when I run this on the website (sites.google.com/view/generator-ad/home), it just prints the word 'null' next to the sentence randomly chosen from 'titleback'. Why does it do this, and not print the name of the product the user inputted at the start? I'm new to javascript and so sorry if the answer is obvious. Any help would be appreciated.
title is a reference to an element. You can't output this to the page.
Instead you presumably want its .value property, to retrieve the value entered by the user.
document.getElementById("Titleback").innerHTML = titleback + title.value;
HtmlInputElement means in this case that you are trying to print out the whole element, instead of the value.
I guess the following example can you help to solve your issue:
Array.prototype.sample = function() { return this[Math.floor(Math.random()*this.length)] };
const submitButton = document.getElementById('submit');
const titleInput = document.getElementById('title');
submitButton.addEventListener('click', e => {
const titleFromArray = ['"Nothing can beat','"How can you not love'].sample();
document.getElementById("Titleback").innerHTML = `${titleFromArray} ${titleInput.value}"`;
});
<input id="title" name="name">
<p id="Titleback"></p>
<button id="submit">Submit</button>
+1 suggestion:
Usually I like better naming convention. For example in this case when you use getElementById then I would suggest to use the variable name with the element type as well. Maybe this is just my personal preference. By doing this you will be sure that you are not mixing up values with DOM elements' references. For example in button case a better name can be just like submitButton. Other example:
const titleInput = document.getElementById('titleInput');
const title = titleInput.value;
I hope this helps!

How to show elements from form in html [closed]

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 4 years ago.
Improve this question
I have this:
<form>
Input name: <input type="text"/><br/>
Input last name: <input type="text"/><br/>
Your age: <input type="number"/><br/>
Your points: <input type="number"/><br/>
Overral: <input type="number"/><br/>
<button type="submit">Submit</button><br>`
What I want to do, so, as you can so i have button sumbit, and I want when i click it to make numbered list of my form. Something like this:
Mark
Williams
....
Try this, it takes all inputs and appends into a list
$(document).ready(function(){
$('button').click(function(e){
e.preventDefault();
$('#a').append('<ol><li>'+$("#name").val()+'</li><li>'+$("#last").val()+'</li><li>'+$("#age").val()+'</li><li>'+$("#points").val()+'</li><li>'+$("#over").val()+'</li></ol>')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Input name: <input type="text" id="name"/><br/>
Input last name: <input type="text" id="last"/><br/>
Your age: <input type="number" id="age"/><br/>
Your points: <input type="number" id="points"/><br/>
Overral: <input type="number" id="over"/><br/>
<button type="submit">Submit</button><br></form>
<div id="a"></div>
At the risk of overly complicated and wordy to newcomers (particularly when compared to 5 lines of jQuery) - here's a plain JavaScript approach with a bit of explanation as to what's going on at every step.
Adding people to the list:
<!--
1 ) Add an ID so we can identify the form
-->
<form id="person-add">
Input name: <input type="text"/><br/>
Input last name: <input type="text"/><br/>
Your age: <input type="number"/><br/>
Your points: <input type="number"/><br/>
Overral: <input type="number"/><br/>
<!-- 2 ) Add an onclick event to run a JavaScript function.-->
<button onclick="addPerson(event);">Submit</button><br>
</form>
<!-- 3 ) Add the list we'll add people to. This has an ID as well.-->
<ol id="person-list">
</ol>
<!-- 4 ) Then the JavaScript function that activates when the button is pressed. -->
<script type="text/javascript">
// It accepts a parameter, 'event' - this is passed from the onclick event.
function addPerson(event){
// By default, clicking a button in a form submits the form to the server.
// Since we're using JavaScript to create the list, we'll prevent that from happening.
event.preventDefault();
// Using querySelectorAll, we get all the input fields within '#person-add'
var person_fields = document.querySelectorAll('#person-add input');
// Here we get the #person-list element we'll be adding the person to.
var person_list = document.getElementById('person-list');
// Create a list item for the person, but don't put it in the list yet.
var person = document.createElement('li');
// Loop through the fields and add their value list item.
for( var field = 0; field < person_fields.length; field++ ) {
// Add the value of the field to the person list item.
person.innerText += person_fields[field].value;
// If the next item isn't the end of the list, we'll add a space.
if( field + 1 !== person_fields.length ){
person.innerText += ' ';
}
}
// Lastly, add the person to the person_list.
person_list.appendChild(person);
}
</script>
Sorting the list by high score:
If you wanted to extend upon this, one thing to do would be to add field names to the input fields, so you could build an array of people and then list them in order of who has the most points.
I'm not going to tell you exactly how to implement this - but here's a few hints to get you started:
Setting field names
<input type="number" name="points"/>
Creating a list of people
// Create an empty list.
var people = [];
Creating an object to respresent a person
// Create an empty object.
var person = {};
Adding values to an object
// Add a property matching the field name with the field value.
person[ person_fields[field].getAttribute('name') ] = person_fields[field].value;
Adding an object to a list
// Add the person to the list of people.
people.push( person );
Draw the list in order of highest points to lowest
Check out Mozilla docs for a breakdown of JavaScript for array sorting.
function updateList(){
// Here we get the #person-list element we'll be adding the person to.
var person_list = document.getElementById('person-list');
// Empty the person_list as we're redrawing it in order.
person_list.innerHTML = '';
// Sort the people list by highest points.
people.sort( function( person1, person2 ) {
return person2.points - person1.points;
} );
// Loop through the fields and add their value list item.
for( var position in people ) {
// Create a list item for the person, but don't put it in the list yet.
var list_item = document.createElement('li');
// Get the person.
var person = people[position];
// Add the value of the field to the person list item.
list_item.innerText += person.firstname + ' ' + person.lastname;
list_item.innerText += ' ( ' + person.points + ' points )';
// Add the list item to the person_list.
person_list.appendChild(list_item);
}
}
Hope this helps!

Javascript/HTML How to remove element of javascript array dynamically through HTML input/text box [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}

Storing user inputs (Q & A ) in an array and retrieve the answer [closed]

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 5 years ago.
Improve this question
I'm a beginner in JavaScript & in this task I have I have to do the following;
allow the user to enter questions and answer pairs in an html page which will be stored in an array.
retrieve the answer when one of the questions from the array is asked (different boxes, labels)
Reset the boxes when I press a button
So far, I just know how to store the user input in one single array, append it when a button is pressed and display it.
How do I have two different objects (Question & answer) in the same array that will be an input by the user in pairs and retrieve only the answer when the Question is input again? It kind of works like a Manual Bot.
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for (i = 0; i < myArr.length; i++) {
pval = pval + myArr[i] + "<br/>";
}
// display array data
document.getElementById('pText').innerHTML = pval;
}
<!DOCTYPE html>
<html>
<head>
<title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="text" id="inputText" />
<button onclick="pushData();">Show</button>
<p id="pText"></p>
</body>
</html>
Why not use an object? That way, you can store the Question/Answer pairs with the Question as the key and the answer as its value. Try this out:
var myObj = {};
function pushData() {
// get value from the input text
var question = document.getElementById('inputQuestion').value;
var answer = document.getElementById('inputAnswer').value;
// add data to the object
myObj[question] = answer;
}
function getAnswer() {
var question = document.getElementById('inputRetrieveQuestion').value;
if (myObj[question]) {
document.getElementById('pText').innerHTML = myObj[question];
}
}
<html>
<body>
<h3> Enter a Question/Answer </h3>
Question <input type="text" name="question" id="inputQuestion" /> Answer <input type="text" name="answer" id="inputAnswer" />
<button onclick="pushData()">Submit</button>
</br>
<h3> Retrieve an Answer </h3>
Question <input type="text" name="question" id="inputRetrieveQuestion" />
<button onclick="getAnswer()">Submit</button>
</br>
Answer:
<div id="pText"></div>
</body>
</html>

Get Data in all Fields [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please help me in this issue
I want to fill all the fields with random data
https://jsfiddle.net/omrmstg7/
<html>
<head>
<script>
//<![CDATA[
window.onload=function(){
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
}//]]>
</script>
</head>
<body>
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
<input type="text" id="my-input" />
<input type="text" id="my-input" />
</body>
</html>
I'm guessing your problem is that you want to fill all the inputs and it doesn't do that.
The problem is that id is reserved for unique elements.
So, if you change your HTML for id to be class instead, you would change your JavaScript to something like this:
var button = document.getElementById("my-button");
var inputs = document.getElementsByClassName("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
Array.prototype.forEach.call(inputs, function (input) {
input.value = names[Math.floor(Math.random() * names.length)];
});
});
Change the inputs to use a class instead of an id.
id values should be unique in HTML and getElementById only returns the first matching id.

Categories