Set input value with text in link with javascript - 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>

Related

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>

Javascript adding li element value to the empty list if it is not existing

I have a problem in Javascript.I am adding new list items to the 'ul' elements and this list is empty at first and I do not want to add same values twice. When I write the if statement I get the exception because my list is empty so the result return null.
How can I fix this this problem?
Thank you in advance...
Html Codes
<input type="text" id="the-filter" placeholder="Search For..." />
<div class="list-container">
<ul id="myList"></ul>
<button id="button">Click</button>
Javascript Codes
let newlist = document.querySelector("#myList");
const li = document.getElementsByClassName('list-group-item');
const button = document.getElementById("button");
const button.addEventListener('click' , listName);
const input = document.getElementById("the-filter");
function listName()
const inputVal = input.value;
for (i = 0; i < li.length; i++) {
if ((li[i].innerHTML.toLocaleLowerCase().includes(inputVal) && inputVal!="") ||
(li[i].innerHTML.toUpperCase().includes(inputVal) && inputVal!="")) {
let newItem = document.createElement("li");
li[i].classList.add("list-group-item");
let textnode = document.createTextNode(li[i].innerHTML.toLocaleLowerCase());
newItem.appendChild(textnode);
if((newlist.children[0].innerHTML.toLocaleLowerCase().includes(inputVal))){
newlist.insertBefore(newItem, newlist.childNodes[0]);
}
}
}
}
If I understood the task correct, you need to add items to the list by button click.
If same item exists (case insensitive), then nothing happens.
const list = document.querySelector("#myList");
const button = document.getElementById("button");
button.addEventListener("click", listName);
const input = document.getElementById("the-filter");
function listName() {
const inputVal = input.value;
const [...lis] = document.getElementsByClassName("list-group-item");
const same = lis.find((el) => el.textContent.toLowerCase() === inputVal.toLowerCase());
if (same) {
return;
}
let newItem = document.createElement("li");
newItem.classList.add("list-group-item");
newItem.textContent = inputVal;
list.appendChild(newItem)
}
<input type="text" id="the-filter" placeholder="Search For..." />
<div class="list-container">
<ul id="myList"></ul>
<button id="button">Click</button>
</div>
You're on the right track with event listeners and element creation, but your original code didn't quite seem to match your stated goal.
Here's a solution you might find useful, with some explanatory comments:
// Identifies some DOM elements
const
input = document.getElementById("my-input"),
newList = document.getElementById("my-list"),
items = document.getElementsByClassName('list-group-item'),
button = document.getElementById("my-button");
// Focuses input, and calls addItem on button-click
input.focus();
button.addEventListener('click', addItem);
// Defines the listener function
function addItem(){
// Trims whitespace and sets string to lowerCase
const inputTrimmedLower = input.value.trim().toLocaleLowerCase();
// Clears and refocuses input
input.value = "";
input.focus();
// Ignores empty input
if (!inputTrimmedLower) { return; }
// Ignores value if a list item matches it
for (const li of items) {
const liTrimmedLower = li.textContent.trim().toLocaleLowerCase();
if (liTrimmedLower === inputTrimmedLower) {
console.log(`${inputTrimmedLower} is already listed`);
return;
}
}
// If we got this far, we want to add the new item
let newItem = document.createElement("li");
newItem.classList.add("list-group-item");
newItem.append(inputTrimmedLower); // Keeps lowerCase, as your original code
newList.prepend(newItem); // More modern method than `insertBefore()`
}
<input id="my-input" />
<ul id="my-list"></ul>
<button id="my-button">Click</button>

Search by pressing the enter key on keyboard

Trying to also search by pressing enter key. Works with the button but for some reason the code i have for the key press is not working.
Javascript:
function displayMatches() {
const searchText = document.querySelector('.search').value;
const matchArray = findMatches(searchText, name);
const html = matchArray.map(place => {
const regex = new RegExp(searchText);
const nameName = place.name.replace(regex, `<span class="hl">${searchText}</span>`);
return `
<a href="${place.url}" target="_blank">
<li>
<span class="name">${nameName} <br> ${(place.price)}</span>
<img src="${place.imgurl}" alt="Drink Image" height="87.5" width="100">
</li>
</a>
`;
}).join('');
suggestions.innerHTML = html;
}
const suggestions = document.querySelector('.suggestions');
const searchBtn = document.querySelector('.btn-search');
searchBtn.addEventListener('click', displayMatches);
var input = document.getElementById('.search');
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('.btn-search').click();
}
});
In:
document.getElementById('.btn-search').click();
Are you sure .btn-search is a id property? Seems like a class property. You cannot get the element with getElementById if the "btn-search" isn't the id of the element.
And you don't need to set "." (class) or "#" (id) on the getElementById (getElementById it's only to get elements by id, so you don't need to tell the script the property type you searching).
As the user William Carneiro stated, the issue is the . character.
The function getElementById just receive the id, not a selector. Check documentation
Change this line:
var input = document.getElementById('.search');
With something like this:
var input = document.getElementById('search');
... or this:
var input = document.querySelector('#search');
Also, make sure that your element has id="search", it seems that probably you want to find an element with the class search instead.
var input = document.querySelector('.search');
I found this and I think it can helped you
JavaScript:
function myFunction(event) {
var x = event.keyCode;
if (x == 27) {
// 27 is the ESC key
alert ("You pressed the Escape key!");
}
}
Ok most of your code was working
A few things to note
When using query selector and calling a class use the class name with the dot'.search-btn'
When using getElementById remember there is no Dot 'search-btn'
Also I think I added an id in few places make sure your html tags have Id attributes to them before using getElementById i.e class='search-btn' id='search-btn' ...>
Other than that your code works
function displayMatches() {
const searchText = document.querySelector('.search').value;
// the rest of your code here
console.log("enter Worked Searching" );
}
const suggestions = document.querySelector('.suggestions');
const searchBtn = document.querySelector('.btn-search');
searchBtn.addEventListener('click', displayMatches);
var input = document.getElementById('search');
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('btn-search').click();
}
});
<input class="search" id = 'search'type="text" placeholder="Search Deals">
<input type='button' class='btn-search' value='search' id ='btn-search'>

Search data from specific DOM part

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.

Undefined result in Console by Input to Array Fields

Why when I pus the Submit button is undefined all of them?
I want to create an array just by using input fields like this.
Is there a nother way to do this?
I tried to do it with Class name and the result is still undefined
function clicked() {
var input_value = document.querySelectorAll('#data, #data1, #data2, #data3, #data4').value;
console.log(input_value)
}
document.getElementById('btn').addEventListener('click', clicked);
<input id="data">
<input id="data1">
<input id="data2">
<input id="data3">
<input id="data4">
<button id="btn">Click me</button>
querySelectorAll will return a "NodeList", which is similar to an array. NodeLists don't have a value property, so it's returning undefined.
If you want to get the value from each of the input boxes, you'll need to loop through the NodeList and pull the value from each HTML element individually.
function clicked() {
var nodeList = document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
for (var i = 0; i < nodeList.length; i++) {
console.log(nodeList[i].value);
}
}
document.getElementById('btn').addEventListener('click', clicked);
Change fn to this:
function clicked() {
var inputs= document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
inputs.forEach(i => {
console.log(i.value);
});
}

Categories