Search data from specific DOM part - javascript

I have a search input field, and I want to get the user's input dynamically and update a list contained in a <div>
I'm setting up a search solution for a catalogue where you can display a list of items.
Right now all the items are shown at once.
the html
<input type="search" id="search-field" placeholder="Search...">
</div>
<div class="container">
<p id="guide">Select a category from the menu</p>
<ul id="product-list">
</ul>
<script src="./preload.js"></script>
</div>
the js code
var fileList = document.getElementById('product-list');
var title = document.getElementById('guide');
title.innerHTML = `You are looking at the ${products} catalog.`;
for(var i = 0; i < thumbFiles.length; i++){
var pathName = thumbFiles[i];
var finalName = pathName.split('/').pop();
fileList.innerHTML = document.getElementById('product-list').innerHTML +
`<li class="product-container">
<div class="new-thumb">
<a href="${(items[i])}" id='product-placeholder' target="_blank">
<img src="${(thumbFiles[i])}" alt="thumb" class="thumbnail">
</a>
<h4>${(path.parse(finalName).name)}</h4>
</li>`
};
}
I expect to update the <ul> with the search input text matching element from the catalogue.

You can attach an oninput listener to your element, like this :
In your js script
const myInput = document.querySelector(‘#search-field’);
const fileList = document.querySelector('#product-list');
myInput.addEventListener(‘input’, () => {
// Don’t forget to clean your results on each new input
fileList.innerHTML = ‘’;
for(const index in thumbFiles) {
const pathName = thumbFiles[index];
const finalName = pathName.split('/').pop();
// Here is the function that will check if your current item match user input
if (match(finalName, myInput.value)) {
fileList.innerHTML += [your stuff]
}
}
});
this will trigger a function each time your input is changing value. Here, it calls our arrow function in which we pack all the actions we want to execute when user input some text.
EDIT
Forgot to compare with current input. You can get input value by calling myInput.value
An example of what match() can be :
function match(name, userInput) {
return name.includes(userInput);
}
This will just check if the finalName contains the user input.

Related

adding delete button to javascript to do list items

I am trying to add delete button to each item in a list. Adding them works as long as I do not have the delete button.
const newcontainer = document.getElementById("toDoContainers");
//gets number of list items in todolist
//adds list item to list
function deleteitem(paramitem){
var element = document.getElementById(paramitem);
element.remove(paramitem);
}
function addnew(){
let numb = document.getElementById("todolistitems").childElementCount;
var listitem = document.createElement("li");
var reallist = document.getElementById("todolistitems");
var inputvar = document.getElementById("inputfield").value;
var node = document.createTextNode(inputvar);
let numbvar = numb +1;
listitem.appendChild(node);
listitem.setAttribute('id', numbvar);
listitem.addEventListener('onClick', deleteitem(listitem));
reallist.appendChild(listitem);
var inputvar = document.getElementById("inputfield").value="";
// node.appendChild(document.createTextNode(inputvar));
/// document.getElementById("toDoContainers").innerHTML=inputvar;
}
<h1>To Do List</h1>
<div class="container">
<input id="inputfield" type="text"><button id="addToDo" onclick="addnew()">Add</button>
<div class="tO" id="toDoContainers">
<ul id="todolistitems">
</ul>
</div>
</div>
I tried a thing where on each list item created, you can 'onclick'=deleteitem(item). I have tried using queryselector, getelementbyId, and queryselectorall in the delete function.
Adding list items works as long as I do not try adding the delete functionality.
There's a few errors in your code.
You've used 'onClick' instead of 'click' for the click event
Your click event assignment is actually running or interpreting the remove function and attempting to use the return value of the function as the click function.
You've also passed in the list item HTML element as opposed to the ID, which the function requires. This function then tries to use the element itself to find the element and then remove a child element with the same parameter - this will always return undefined.
You need to wrap this in another function that returns the function to be performed on click, and fix that error, as below:
const newcontainer = document.getElementById("toDoContainers");
//gets number of list items in todolist
//adds list item to list
function deleteitem(paramitem) {
var element = document.getElementById("list" + paramitem);
element.remove();
}
function addnew() {
let numb = document.getElementById("todolistitems").childElementCount;
var listitem = document.createElement("li");
var reallist = document.getElementById("todolistitems");
var inputvar = document.getElementById("inputfield").value;
var node = document.createTextNode(inputvar);
let numbvar = numb + 1;
listitem.appendChild(node);
listitem.setAttribute("id", "list" + numbvar);
listitem.addEventListener("click", function () {
deleteitem(numbvar);
});
reallist.appendChild(listitem);
var inputvar = (document.getElementById("inputfield").value = "");
// node.appendChild(document.createTextNode(inputvar));
/// document.getElementById("toDoContainers").innerHTML=inputvar;
}
<h1>To Do List</h1>
<div class="container">
<input id="inputfield" type="text"><button id="addToDo" onclick="addnew()">Add</button>
<div class="tO" id="toDoContainers">
<ul id="todolistitems">
</ul>
</div>
</div>

Building a keyboard and missing onclick event

I'm building a virtual keyboard with vanillla javascript but don't know where to add the onclick event listener to the buttons or how to grab them. I have a printKeys function that loops thru the array and prints them onload, and I have an unfinished typeKeys function where I'm trying to grab the innerhtml and print it to the input field.
HTML
</head>
<body onload="printKeys()">
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here.."></input>
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>
<script src="index.js"></script>
</body>
</html>
Javascript
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.getElementById("keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
//add onclick function to button
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys() {
console.log("clicked")
//grab input and replace with button innerhtml
}
Instead of adding the event handler to each button, you can apply it to the parent (keyboard) then just use the event's target to get the specific button. I also added the character to a data-attribute instead of the innerHTML.
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.querySelector(".keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
keys.setAttribute("data-character",alphaKeys[i]);
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys(character) {
input.value += character;
}
keyboard.addEventListener("click",function(e){
let target = e.target;
if(target.getAttribute("data-character")){
typeKeys(target.getAttribute("data-character"))
}
});
printKeys();
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here..">
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>

I am trying to remove Items from a list with an on-click, what am I missing?

I am trying to remove an item every time it is clicked on but only a single item at a time (the item that was clicked on) when trying to make a 'to-do' list. I can easily remove all simultaneously but I am having a lot of issues trying to do it at an individual level. I thought this would work but hoping to get a second set of eyes on it.
var toDoCount = 0;
var todoarray = [];
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
todoarray.push(value);
console.log(todoarray);
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#item-" + toDoNumber).remove();
});
});
}
HTML is below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
don't need the number, just the element.
change...
$("#item-" + toDoNumber).remove();
to...
$(this).remove();
e.g.
$(document.body).on("click", ".checkbox", function() {
$(this).remove();
});

Search function filter li's in pure Js

I'm trying to make an input that filters a <ul> based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.
Here is my function:
var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}
My HTML for the search bar:
<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>
My HTML for one of the li's:
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>
I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...
Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010
Any help or comments on my code is very appreciated.
There were several issues:
stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.
Otherwise it more or less worked, good job.
I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.
Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;

Set input value with text in link with javascript

I have an input field <input type="text" name="input">.
I also have some links:
<div>
first link
second link
...
</div>
I want to let the user click on a link and set the value of the input with the value in the link.
I guess I should do something like:
const input = document.getElementById('input');
document.getElementsByTagName('a').forEach(function () {
this.onclick = function () {
input.value = this.innerHTML();
}
});
but I know that document.getElementsByTagName('a') doesn't return an array, so it's not possible, and I am not sure if this is the right approach.
getElementsByTagName() returns an HTMLCollection.
The usage as per the docs:
The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.
// document.forms is an HTMLCollection
elem1 = document.forms[0];
elem2 = document.forms.item(0);
alert(elem1 === elem2); // shows: "true"
This means that you should be able to treat your result like an array (including using .length).
Firstly, Dom lists are not normal array's, so forEach won't work.
Secondly, innerHTML is not function, it's property..
The [].slice.call, can be used to convert into a normal array.
Try this below. ->
const input = document.getElementById('input');
[].slice.call(document.getElementsByTagName('a')).
forEach(function (e) {
e.onclick = function (evt) {
evt.preventDefault();
input.value = this.innerHTML;
}
});
<div>
first link
second link
</div>
<input id="input" type="text">
Try this below:
https://jsfiddle.net/7h1a3p4x/5/
var el = document.getElementsByClassName("link");
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('click', sendData, false);
}
function sendData() {
var input = document.getElementById("myinput");
input.value = this.innerHTML;
}
<input id="myinput" type="text" name="name" />
<div>
<a class="link" href="#">LINK 1</a>
<a class="link" href="#">LINK 2</a>
</div>

Categories