I am using javascript to autopopulate a select box on focus, then clear the innerHTML (except for the selected value) on blur (to keep the list from getting bigger and bigger).
Everything works as expected unless the value selected is two words... eg:"Bath Bombs". If I click the select box again, and select the same option (now at the top of the list) it drops the word "bombs" from the field???
(also, with the code as I have it, is there any way to keep the field from shrinking?)
Can someone please tell me where I have gone wrong?
(btw: I know very little javascript or html - I have been teaching this to myself over the last few days)
<script>
function prodType(id){
var targetId = id;
var select = document.getElementById(targetId);
var options = [ "", "Candles", "Tarts", "Bath Salts", "Bath Bombs", "Glycerin Soaps", "Salt Scrubs", "Sugar Scrubs", "Shower Gel", "Lotions"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function clearAll(id) {
var targetId = id;
var select = document.getElementById(targetId);
var svalue = select.value;
select.innerHTML = "<option value="+svalue+">"+svalue+"</option>";
}
</script>
<select style="width:150" id="selectNumber" onfocus="prodType(this.id)" onblur="clearAll(this.id)">
<option value="" hidden>Product Type</option>
</select>
If you run this code... select a "two word" option, click off the select box, then select the same option again, this time from ~~THE TOP~~ of the list.
When you click off you will see what's happening.
Thanks!
The problem is that when you are updating the option value, you aren't including the quotes so it's essentially being set as value=bath bombs. The bombs gets ignored and you just end up with value=bath. Add some quotes (value='bath bombs') and it will work as expected.
function prodType(id){
var targetId = id;
var select = document.getElementById(targetId);
var options = [ "", "Candles", "Tarts", "Bath Salts", "Bath Bombs", "Glycerin Soaps", "Salt Scrubs", "Sugar Scrubs", "Shower Gel", "Lotions"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function clearAll(id) {
var targetId = id;
var select = document.getElementById(targetId);
var svalue = select.value;
select.innerHTML = "<option value='"+svalue+"'>"+svalue+"</option>";
}
<select style="width:150" id="selectNumber" onfocus="prodType(this.id)" onblur="clearAll(this.id)">
<option value="" hidden>Product Type</option>
</select>
You can use such variant with single quotes:
select.innerHTML = "<option value='"+svalue+"'>"+svalue+"</option>";
Related
I'm new to JS and I'm trying to populate a dropdown menu with items from an array but every time I loop through the array it displays letter after letter rather than the full string. Please let me know what am I doing wrong. Thank you
JS:
var ProjectNames = [];
ProjectNames = CProject;
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
HTML:
<select id="ProjectList" onchange="AddHoursForm()">
<option> --Choose Project-- </option>
</select>
Data in array is coming from Firebase. If I print console.log(ProjectNames) it gives the array objects but if I do console.log(ProjectNames[i]) it prints it letter by letter.
It seems to be working for me. Make sure you are working with an array.
var ProjectNames = [];
ProjectNames = ["hello", "world"];
console.log(ProjectNames) // <--- check this is this array?
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="ProjectList" onchange="AddHoursForm()">
<option> --Choose Project-- </option>
</select>
You killed the contents of ProjectNames setting it equal to CProject.
If you want to add itemns to ProjectNames use push or ProjectNames[ProjectNames.length]=... as below: The rest is ok.
var CProject="four";
var ProjectNames = ["one","two","three"];
ProjectNames[ProjectNames.length]=CProject;
ProjectNames.push("five");
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
It would be really easy for you if you use template strings or template literals for achieving this.
Just get data, create element, append it upon your ease.
// selecting div ith id = "main"
const main = document.querySelector("#main");
// you data from firebase or any other data source
let data = ["option1", "option2"];
// creating an element using tamplate string
const mySelectElement = `
<select>
<option value="" disabled selected>Choose a option</option>
${data.map(option => `<option value="${option}">${option}</option>`).join('')}
</select>
`;
//appeding element
main.innerHTML = mySelectElement;
<div id="main">
</div>
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="selectStock">
<option>Choose a stock</option>
</select>
I have multiple Javascript arrays of data (pulled from Excel) and have different functions that basically make calculations based on the row of the array. For example:
var stocks = [['Apple',100,8998,723,7212]['Microsoft,928,1992,821,2381]]
What I need to do is make a dropdown menu that will allow a user to select an option (Microsoft or Apple) and then based on this selection, will pull this value into the formula to make the calculations
document.write(Math.round(stocks[i][1] * 100)/100 + " dollars per share");
where i is the variable based off dropdown menu selection. Does this make sense? I'm not sure how to approach this, it's for a personal project. Thanks for the help!
https://jsfiddle.net/b22y3v85/
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.write(Math.round(stocks[index][1] * 100)/100 + " dollars per share");
};
Here is a working example, although you'll probably want to do something other than document.write the result.
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function getPrice(stock) {
var price = false;
for (var a = 0; a < stocks.length; a++) {
if (stocks[a][0] == stock) {
price = stocks[a][1];
break;
}
}
if (!price) { alert("Incorrect choice."); return; }
document.getElementById("result").innerText = stock + " is currently " + (Math.round(price * 100)/100 + " dollars per share");
}
<select id="selectStock" onchange="getPrice(this.value);">
<option>Choose a stock</option>
</select>
<br><br>
<div id="result"></div>
EDIT: Shows result in a div on the page, instead of overwriting the page with document.write().
<select id="selectStock"></select>
<script type="text/javascript">
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.innerHTML = opt;
el.value =stocks[i]+'';
select.appendChild(el);
}
select.addEventListener('change', function(e){
var val = e.currentTarget.value;
val = val.split(',');
val.shift();
callYourMethod(val);
});
</script>
var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});
Now with each city i want to store my circle name. and save it as an attribute and pass when the city is selected
You can Hardcode a custom attribute to a select's option. For example,
<option circle="UP" value="Lucknow">Lucknow</option>
and get it's value with jquery like this,
var circle = $('option:selected', this).attr("circle");
HTML
<select name="cityDropdown">
<option circle="UP" value="Lucknow">Lucknow</option>
<option circle="Bihar" value="Patana">Patana</option>
<option circle="Punjab" value="Chandigarh">Chandigarh</option>
</select>
Javascript
$('select[name="cityDropdown"]').change(function(){
var cityName = $(this).val();
var circle = $('option:selected', this).attr("circle");
console.log(cityName + " : " + circle);
});
Note : You can also use other custom attribute (custom attribute city for example). But you just need to use city as value of the option.
Here is the fiddle.
make a proper selector ..try this ..
$('#selectCity').change(function(){
cityName = $(this).val();
console.log(cityName); // do something
});
HERE is the fiddle..
var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
element.setAttribute('circle-name', 'your value'); // your attribute
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});
var optionAttr = $('#cityDropdown option:selected').attr("circle");
var optionAttr1 = $(this).find('option:selected').attr("circle");
i'm trying to place a list of items onto a dropdown box but having little success. I have my list of items labelled MARKET, and i have a drop box using the "select" element, i've been trying all sorts of elements like .value and .option and .setAttribute but i dont know how to formulate the code using them, if there are any other elements i should be looking at then i would certainly like to know for future reference, but for the moment i would like to know how i can change my code so i can put a list of items onto a dropdown box !! Appreciate the help if there is any !!
var lbldiv = document.createElement("div");
var mklbl = document.createElement("label");
mklbl.innerHTML = "Market ";
var mkslct = document.createElement("select"); //dropdown
lbldiv.appendChild(mklbl);
lbldiv.appendChild(mkslct);
document.body.appendChild(lbldiv);
var markets = ["UK", "USA", "China"]; //list of markets
var mkul = document.createElement("ul"); //formulated list
mkul.className = "mkul";
for(var i = 0; i < markets.length; ++i){
var crtli = document.createElement("li");
crtli.value = i;
crtli.innerHTML = markets[i];
mkul.appendChild(crtli);
}
document.body.appendChild(mkul);
function populateDDLB() {
var selectEl = document.getElementById("dropdownlistbox");
var options = ["A", "B", "C", "D"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
selectEl.appendChild(el);
}
}
window.onload = populateDDLB;
I am trying to make auto complete to select option according to input from the user
something like
<input type=text onkeyup=findit()>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
.
.
.
<select>
I found this code 'but it only work on one select in the page( I need multi select)
<html>
<head>
<script type="text/javascript">
//initialize some global variables
var list = null;
function fillit(sel,fld) {
var field = document.getElementById("entry");
var selobj = document.getElementById("sel");
if(!list)
{
var len = selobj.options.length;
field.value = "";
list = new Array();
for(var i = 0;i < len;i++)
{
list[i] = new Object();
list[i]["text"] = selobj.options[i].text;
list[i]["value"] = selobj.options[i].value;
}
}
else
{
var op = document.createElement("option");
var tmp = null;
for(var i = 0;i < list.length;i++)
{
tmp = op.cloneNode(true);
tmp.appendChild(document.createTextNode(list[i]["text"]));
tmp.setAttribute("value",list[i]["value"]);
selobj.appendChild(tmp)/*;*/
}
}
}
function findIt(sel,field)
{
var selobj = document.getElementById("sel");
var d = document.getElementById("display");
var len = list.length;
if(field.value.length > 1)
{
if(!list)
{
fillit(sel,field);
}
var op = document.createElement("option");
selobj.options.length = 1
var reg = new RegExp(field.value,"i");
var tmp = null;
var count = 0;
var msg = "";
for(var i = 0;i < len;i++)
{
if(reg.test(list[i].text))
{
// d.childNodes[0].nodeValue = msg;
tmp = op.cloneNode(true);
tmp.setAttribute("value",list[i].value);
tmp.appendChild(document.createTextNode(list[i].text));
selobj.appendChild(tmp);
}
}
}
else if(list && len > selobj.options.length)
{
selobj.selectedIndex = 0;
fillit(sel,field);
}
}
</script>
</head>
<body onLoad="fillit(sel,entry)">
<div>Enter the first three letters of a street and select a match from the menu.</div>
<form>
Street
<input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
<option value="s0003">bol</option>
<option value="s0004">col</option>
<option value="s0005">dol</option>
<option value="s0007">Cooper</option>
<!--and so on and so forth-->
</select>
</form>
</body>
Any Ideas How to make it work on multi select on the page?
Thanks
Baaroz
Not sure if this would work for you, but chosen.js has a really nice autocomple multi select
http://harvesthq.github.com/chosen/
Usually Autocomplete is for single values, but the jQuery UI autocomplete does have a multiple select function. Perhaps try that? Minimum effort coding for you that way.
An odd way to do that is to change the ID in the script and copy it the number of times you want to use this options in the page. so for example:
select id="sel1"
select id="sel2"
select id="sel3"
and then. copy the script and replace every (sel) with sel1 past it again and replace (sel) with sel2 and so on.
not the best solution but it will work.
Good Luck