dropdown list from text input - javascript

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>

Related

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

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!

Allow user to delete an option element in html

What I am trying to achieve is a dropdown menu whose options the user will create by inputting the text content of the option they want to create. I have achieved this but what I want is that the user can delete an option if. I cant figure out how to do this. Help please. Buttons, input fields, anything is fine, but please use vanilla Javascript.
<!DOCTYPE html>
<html>
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
</div>
<script>
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
</script>
</html>
This is one of the procedures you can follow:
Create a function called deleteOption
Inside function, loop through the selectBoxElem variable and find the selected option. Then Remove the element
Attach the function to a button.
Example:
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
function deleteOption() {
const selectBoxElem = document.getElementById("sel");
for (var i = 0; i < selectBoxElem.length; i++) {
if (selectBoxElem.options[i].value == selectBoxElem.value)
selectBoxElem.remove(i);
}
}
<!DOCTYPE html>
<html>
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
<button id="button" onclick="deleteOption()">
Delete Selected Option
</button>
</div>
</html>
select element has options collection. The collection has remove method. You can use it like so;
const select = document.querySelector('select'),
options = select.options;
options.remove(select.selectedIndex);
Here is a complete solution which I rewrote to use eventListeners
document.getElementById("name").addEventListener("click",function(e) {
const tgt = e.target;
const src = document.getElementById('inputname');
const sel = document.getElementById("sel");
const inputval = src.value;
src.value="";
if (tgt.id==="add") {
if (sel.querySelector("option[value="+inputval+"]")) {
alert("That already exists")
}
else {
sel.options[sel.options.length] = new Option(inputval,inputval)
sel.value = inputval; // focus the new value
}
}
else if (tgt.id==="del") {
if (sel.selectedIndex === 0) return;
if (inputval) sel.value = inputval; // if filled in, we use it
const curOpt = sel.options[sel.selectedIndex]; // in any case remove the selected option
if (curOpt) {
curOpt.remove();
sel.selectedIndex = -1;
}
}
})
<div id="name">
<select id="sel"><option value="">Please select</option></select>
<input type="text" class="auto-save" id="inputname">
<button type="button" id="add">Create Option</button>
<button type="button" id="del">Remove Option</button>
</div>
Here you go with a solution
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
function deleteOption() {
const element = document.getElementById("sel");
element.remove(element.selectedIndex);
}
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
<button id="button" onclick="deleteOption();">
Delete Option
</button>
</div>
Documentation: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_remove
use this:
function RemoveOption(){
var Element = document.getElementById("sel");
Element.remove(Element.selectedIndex);
}
Create new button in html
<button id="button" onclick="remove(document.getElementById('inputname').value);document.getElementById('inputname').value='';">
Delete Option
</button>
And add js function
function remove(val) {
var selectobject = document.getElementById("sel");
for (var i=0; i<selectobject.length; i++) {
if (selectobject.options[i].value == val)
selectobject.remove(i);
}
}

How to copy a string from a <div> and past in an <input>?

Code of Note i want copy is : <strong title="Note VF" class="note-a-copier" style="cursor: pointer;" data-clipboard-text="7.6">7.6</strong>
I copy the Note with : data-clipboard-text
Normally past on :
HTML :
<select>
<option id="note-a-coller"></option>
</select>
JavaScript :
<script>
const btnsnote = document.getElementsByClassName('note-a-copier');
for(btn of btnsnote) {
btn.addEventListener(\'click\', elt => {
const input = document.getElementById('note-a-coller');
select.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
</script>
But when I click on the note, it should stick directly in the but it doesn't work.
Example Working Code : https://jsfiddle.net/rjds289g/
const btnsadp = document.getElementsByClassName('adp-a-copier');
for(btn of btnsadp)
{
btn.addEventListener('click', elt => {
const input = document.getElementById('adp-a-coller');
input.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Past : <input type="text" size="40" name="annee" value="" id="adp-a-coller" required />
On JSFiddle : https://jsfiddle.net/rjds289g/3/
I want like this, but with < select > and i don't know how to do this, so if anyone can help me :)
Select value will change with any value inside of it .. in your case the value isn't an option in a select so you need to append it first
const btnsadp = document.getElementsByClassName('adp-a-copier');
for(btn of btnsadp)
{
btn.addEventListener('click', elt => {
var The_Select = document.getElementById('adp-a-coller'),
The_Text = document.createTextNode(elt.target.dataset.clipboardText),
The_option = document.createElement("OPTION");
The_option.appendChild(The_Text);
The_Select.appendChild(The_option);
The_Select.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Past : <select id="adp-a-coller"><option>1</option></select>
And this is the jquery version for me it's much easier to work with
$(document).on('click' , '.adp-a-copier' , function(){
var $this = $(this),
text = $this.data('clipboard-text');
if(!$this.hasClass('appended')){
$this.addClass('appended');
$('#adp-a-coller').append('<option value="'+text+'">'+text+'</option>').val(text);
}else{
$('#adp-a-coller').val(text);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Copy : <div class="adp-a-copier" data-clipboard-text="2003" style="cursor: pointer;">2003</div>
Copy : <div class="adp-a-copier" data-clipboard-text="2005" style="cursor: pointer;">2005</div>
Past : <select id="adp-a-coller"></select>
Explanation : I used the appended class in jquery snippet to append the text just one time to the select even you keep clicking it will remain just one append
Read about how to fill a select with JS. the logic is easy.
You just have to add the div content in an array and after it refill combo with your array content

Reading user input until button pressed javascript

I am new to web development, I have a requirement to read user input one after the other as the add button is clicked,until stop button is pressed and then display the user input in a list. How do I do it ?
<Title>To Do List</Title>
<Body>
<Button id = "AddBtn" onClick = "Store()">Add</Button>
<Button id = "StopBtn" onclick = "Display()">Stop</Button>
<input id = "ip" type = "text" >
<script>
function Store()
{
var tasks;
tasks.push(document.getElementById('ip'));
}
function Display()
{
var i;
for(i=0;i<tasks.length;i++)
{
document.write(tasks[i]);
}
}
</script>
</Body>
<!Doctype html>
<html>
<head>
<Title>To Do List</Title>
</head>
<Body>
<Button id="AddBtn" onclick="Store()">Add</Button>
<Button id="StopBtn" onclick="Display()">Stop</Button>
<input id="ip" type="text">
<ul id="list">
</ul>
<script>
var tasks = [];
function Store() {
tasks.push(document.getElementById('ip').value);
document.getElementById("ip").value = "";
}
function Display() {
var i;
for (i = 0; i < tasks.length; i++) {
var item = document.createElement("li");
var text = document.createTextNode(tasks[i]);
item.appendChild(text);
document.getElementById("list").appendChild(item);
}
tasks = [];
}
</script>
</Body>
</html>
Javascript is case sensitive language.onClick supposed to be
onclick.
you want to store more than one value.You need a array not a
variable.
you want to save just the values in the array not the whole element.
you want to clear the input value after adding it to task array.
you need to get values from your array and create li elements with
value.
you need a parent for your li items which can be ul,ol or div.
you have to add all created li elements to the parent.
after the loop finishes you can clear the array in display method.

removeChild only works once

I have a test input form where a child select box is created depending on the value of one of the choices in the parent select box. Selecting any of the other choices in the parent select box should remove the child. It works, but only once. If the child select box is created a second time, then it is not removed by selecting one of the other choices.
Here is the code:
<html>
<SCRIPT LANGUAGE="JavaScript">
function createtext(){
var var1 = document.getElementById('s');
var var2=var1.value;
if (var2 == "American Express")
{
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
}
else
{
myform.removeChild(gift);
}
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="myform">
<SELECT id = "s" name="s" size=3 onChange="createtext()" ><OPTION>Visa Card<OPTION>Mastercard<OPTION>American Express</SELECT>
</form>
</html>
And here it is in action... http://www.crazyforstamps.com/test-form-6.htm
Try
var gel = document.getElementById('gift');
if(gel){
myform.removeChild(gel);
}
Update:
<!DOCTYPE html>
<html>
<head>
<script>
function createtext() {
var var1 = document.getElementById('s');
var var2 = var1.value;
if (var2 == "American Express") {
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
} else {
<!--myform.removeChild(gift);
var gel = document.getElementById('gift');
if (gel) {
myform.removeChild(gel);
}
}
}
</script>
</head>
<body>
<form action="" method="get" name="myform">
<SELECT id="s" name="s" size=3 onChange="createtext()">
<OPTION>Visa Card</OPTION>
<OPTION>Mastercard</OPTION>
<OPTION>American Express</OPTION>
</SELECT>
</form>
</body>
</html>
Demo: Plunker
Assuming you have defined gift somewhere which I don't see it in the question.
Removing all child elements
var gift = document.getElementById("gift");
while (gift.firstChild) {
gift.removeChild(gift.firstChild);
}
Or another alternative is to simply assign innerHTML to an empty string
var gift = document.getElementById("gift");
gift.innerHTML = '';
First of all you have to keep in mind, that each browser has it's own js compiler. Some can use properties without getting browsers dom element via JS, by just referencing their name. But in order to write all browsers supported code, you have to keep in mind JS specifications.
In your current example on JSFiddle you have to always get your elements before you try to perform any actions on them.
var myform = document.getElementById('myform');
var gift = document.getElementById('gift');

Categories