Is there a way to make a search bar like this? - javascript

So i am making a search bar with javascript and jquery and i loop through a list of objects and an if statement checks if the input value includes something in my array. Then if it does include the item will get added to a select as an option and if the user removes the characters in the input the list would be empty.
But i can't seem to make it work.
This is what i've got:
<input class="type" value="" />
<select class="opties">
</select>
$('.type').on('keyup', function() {
let input = $('.type').val().toLowerCase();
let pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
for(let i=0; i<pc.length;i++) {
if(!pc[i].toLowerCase().includes(input)) {
$('.opties').remove(pc[i])
} else {
$('.opties').append("<option>"+pc[i]+"</option>")
}
if(input == '') {
$('.opties').empty();
}
}
})
The output right now is a few options that are duplicates of each other.

Another approach is to filter() your array and insert new options each update.
You may want to throttle or debounce this to give user time to type
let $sel = $('.opties')
$('.type').on('input', function() {
$sel.empty()
let input = $('.type').val().trim().toLowerCase();
let pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
if (input.length) {
const filtered = pc.filter(v => v.toLowerCase().includes(input));
const opts = filtered.map(v => new Option(v, v));
$sel.append(opts)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type" value="" />
<select class="opties">
</select>

Something like this?
const pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
$('.type').on('keyup', function() {
const input = $('.type').val().toLowerCase();
for (let option of pc) {
$(`.opties option[name='${option}']`).remove()
if (option.toLowerCase().includes(input) && input.length)
$('.opties').append(`<option name='${option}'>${option}</option>`)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type" value="" />
<select class="opties"></select>
Main problem is that $('.opties').remove(pc[i]) is not working. You are trying to remove the select-element instead of its children. Give them name attributes, this is a good way to go!

Related

How to turn a list of strings to an array in javascript

I am trying to code a program which when a user inputs some numbers it will reverse it it and display it on the page. I have to tried to use 'Object.assign', but it doesn't work for me. I have also tried '.toArray', but it still doesn't work(maybe my formatting is wrong?). I am just a beginner so go easy on me. Thanks for t. This is what i have so far:
not working code but what i wanted
This works though:
Working code but not what i wanted
edit: when I reread the question, I realized you wanted the array in reverse. Updated answer at the bottom.
press enter to add the input. If you don't want only numbers delete type='number'.
var arr = [];
const input = document.getElementById('inpt');
input.addEventListener("keydown", event => {
if (event.keyCode === 13) {
arr[arr.length]=input.value;
input.value="";
console.log(arr);
}
});
<input placeholder="Enter a number" type='number' id ='inpt'/>
var arr = [];
const input = document.getElementById('inpt');
const output = document.getElementById('output');
input.addEventListener("keydown", event => {
if (event.keyCode === 13) {
arr[arr.length]=input.value;
input.value="";
var arr2= [...arr].reverse();
output.innerHTML='';
arr2.forEach(element => output.innerHTML+= element+' ');
console.log(arr);
}
});
<input placeholder="Enter a number" type='number' id ='inpt'/>
<div id = 'output'>
</div>

dropdown list from text input

I do not even know how to begin that is why I am not adding code. But I need to create a dropdown name with names the user has entered before, and I know how to make a dropdown list but I do not know how to make the names the user enteres as elements in the dropdown. Thank You
if you store the names in an array you could try something like
let dropdown = document.querySelector('select')
let names = ['john', 'alex', 'alissa', 'sam']
names.forEach(name => {
let option = document.createElement('option')
option.value = name
option.innerText = name
dropdown.append(option)
})
<select></select>
Create a text input a button and select. On click of the button trigger a function which will take the value from the input.Create an array which will store all the text input. If the array already contains the value entered through text input , then dont add it again.Else call the function to take text input and remove white space. Then call another function which will loo through this array and during each iteration it will create a option using document.createElement and will append itself to the select.
let optionArray = [];
function addToOption() {
const inputValue = document.getElementById("userName").value.trim();
if (optionArray.indexOf(inputValue) === -1) {
optionArray.push(inputValue)
}
addToSelect();
}
function addToSelect() {
if (optionArray.length === 0) {
return;
}
const selectBox = document.getElementById('selectOption');
selectBox.innerHTML = '';
optionArray.forEach((item) => {
const elem = document.createElement('option');
const optionText = document.createTextNode(item);
elem.appendChild(optionText);
elem.id = optionText;
selectBox.appendChild(elem)
})
}
<input type="text" id="userName">
<button type="button" onClick="addToOption()">Add</button>
<select id="selectOption"></select>
Here is the Jquery code sample:
<!DOCTYPE html>
<html>
<head>
<title>Update list item</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous">
</script>
</head>
<body>
<input type="text" name="listitem" id="content">
<button id="updateBtn">Add to list</button>
<hr>
<select id="listelement">
<option>test option</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$("#updateBtn").click(function(){
var content=$("#content").val();
var listitem='<option>'+content+'</option>';
$("#listelement").append(listitem);
});
});
</script>
</body>
</html>

How to query multiple elements that start with the same ID and then check whether the input has changed

I have a list of text inputs which all start with the same id but are slightly different at the end. When text is entered by the user in any of these input fields I want to execute a function. At the moment this is working with the following code:
var heightInches = document.querySelector("#Height_Inches");
var heightFeet = document.querySelector("#Height_Feet");
var heightCentimeters = document.querySelector("#Height_Centimeters");
heightInches.oninput = function (e) {
console.log("Edited");
}
heightFeet.oninput = function (e) {
console.log("Edited");
}
heightCentimeters.oninput = function (e) {
console.log("Edited")
}
The issue is that I don't like the repetition and would rather query all of the ids that begin with "Height_" and do something (as what is excuted inside each function will be the same.
Here is what I have tried but does not work:
var allHeight = document.querySelector('[id*="Height_"]');
allHeight.oninput = function (e) {
console.log("edited");
}
I have also tried the same with querySelectorAll
Please could someone help with where I am going wrong here? Every other Stack Overflow answer and article I see seems to suggest that id* is the correct way to select? Thank you
If I understand correctly, this is what you are looking for.
The only thing you were missing is looping through your elements.
const inputs = document.querySelectorAll('[id*="Height_"]');
inputs.forEach( input => {
input.oninput = function (e) {
console.log("edited");
}
})
<input type="text" id="Height_1">
<input type="text" id="Height_2">
<input type="text" id="Height_3">
Rather than use an ID, which is intended to be unique, why not add a class like .height-input to each input and then you can select them all?
// Get elements
const inputs = document.querySelectorAll('.height-input');
const outputEl = document.querySelector('.output');
// Attach event handlers
for (let i = 0; i < inputs.length; i++) {
inputs[i].oninput = function(e) {
// Handle input
outputEl.innerHTML = `Input received on #${e.target.id}`;
}
}
.output {
margin-top: 10px;
}
<input type="text" class="height-input" id="HeightInches">
<input type="text" class="height-input" id="HeightFeet">
<input type="text" class="height-input" id="HeightCentimeters">
<div class="output">Waiting for input...</div>

Passing user HTML input as javascript function argument

I have this line of javascript:
stave.addClef("treble").addTimeSignature("4/4");
Based on what the user types as input in the HTML document, I'd like to change "4/4" to "3/4," or any other fraction that the user comes up with. What is the easiest way to make this conditional substitution?
Thanks,
Nakul
Here's an option that'll allow a user to toggle number inputs up and down:
<input type="number" id="fraction-1"/>
<input type="number" id="fraction-2"/>
Current Signature:
<div id="current-sig"></div>
Then in your javascript...
// Get the select form element
const FRACT_1 = 'fract-1'
const FRACT_2 = 'fract-2'
const fract1 = document.querySelector(`#${FRACT_1}`)
const fract2 = document.querySelector(`#${FRACT_2}`)
const currentSigDiv = document.querySelector('#current-sig')
let currentSignature = '4/4'
const changeSignatureByFraction = ({target}) => {
if(target.id === FRACT_1)) {
currentSignature = `${target.value}${currentSignature.substring(1)}`
stave.addClef("treble").addTimeSignature(currentSignature)
currentSigDiv.innerHTML = currentSignature
} else {
currentSignature = `${currentSignature.slice(0, -1)}${target.value}`
stave.addClef("treble").addTimeSignature(currentSignature)
currentSigDiv.innerHTML = currentSignature
}
}
// Listen for a change event
fract1.addEventListener('change', changeSignatureByFraction)
fract2.addEventListener('change', changeSignatureByFraction)
currentSigDiv.innerHTML = currentSignature
Create a dropdown list with possible fractions.
Query its value into the variable.
Pass the variable as an argument for addTimeSignature() method.
HTML:
<select id="TimeSignatureSelect">
<option value='1/4'>1/4</option>
<option value='2/4'>2/4</option>
<option value='3/4'>3/4</option>
<option value='4/4'>4/4</option>
</select>
JS:
const timeSig = document.getElementByID('TimeSignatureSelect').value;
stave.addClef("treble").addTimeSignature(timeSig);

Having trouble displaying an array value within console.log event using .push function in Jquery

The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">

Categories