Select element is not appending addEventListener - javascript

I'm trying to create a select element and add an 'input' event to it. Everything with JavaScript as showed below:
function showSelectedOption(str) {
alert(str);
}
var list = document.createElement("select");
list.id = "listId";
list.addEventListener('input', showSelectedOption(this.selectedIndex));
for (var i = 0; i < 3; i++) {
var option = document.createElement("option");
option.value = "none";
option.text = "text";
list.appendChild(option);
}
document.body.appendChild(list);
However, when I inspect the element the input event is not appended.
How can I solve this issue?

A couple of issues.
You are not binding the showSelectedOption function, you instead call it and use its returned value (which is undefined) as the event handler.
So pass showSelectedOption without calling it.
Then you will have to find the selectedIndex of that element inside the method, by using the event passed to the function when the input event is triggered.
function showSelectedOption(event) {
var element = event.target,
index = element.selectedIndex,
value = element.options[index].value;
alert(value);
}
var list = document.createElement("select");
list.id = "listId";
list.addEventListener('input', showSelectedOption);
for (var i = 0; i < 3; i++) {
var option = document.createElement("option");
option.value = "none";
option.text = "text";
list.appendChild(option);
}
document.body.appendChild(list);

You can make this work by using setAttribute instead and set the value of the oninput attribute to be the string (not the function) showSelectedOption(this.selectedIndex).
function showSelectedOption(str) {
alert(str);
}
var list = document.createElement("select");
list.id = "listId";
list.setAttribute('oninput', "showSelectedOption(this.selectedIndex)");
for (var i = 0; i < 3; i++) {
var option = document.createElement("option");
option.value = "none";
option.text = "item"+i;
list.appendChild(option);
}
document.body.appendChild(list);

Related

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

Changing select option text color property within manually insert

I'm trying to change text color inside an option with the style.color property while inserting in to a select without success.
its working on browser but not on mobile device
for(var i = 0; i < 4; i++) {
var x = document.getElementById("selectCode");
var option = document.createElement("option");
option.value = i;
option.text = i;
option.style.color = 'darkblue';
x.add(option);
}
Is style.color = 'colorname' property approachable with javascript on mobile device, if not what is the approachable way?
Here is my Jsfiddle
You are changing the color of the option when they are added. You have to add the options first to change the style of the option. Simply change option.style.color to x.style.color and put it at the bottom of the for-loop
Javascript
for(var i = 0; i<4; i++) {
var x = document.getElementById("selectCode");
var option = document.createElement("option");
option.value = i;
option.text = i;
x.add(option);
x.style.color = "#0000FF";
}
Fiddle: https://jsfiddle.net/LL6ued7f/3/

Why won't the addEventListener trigger on change?

Trying to get the eventlistener to run, i.e. when I select United Kingdom, another selection box will appear to select county (county() function), but for some reason the addEventListener will not call the function, and I can't fathom how to pass the selected country to the county function? Any ideas please.
function countries() {
xmlRequest("countries.xml");
var country_selector = document.createElement("SELECT");
country_selector.id = "cou n tryselection";
document.getElementById("quiz").appendChild(country_selector);
var t = document.getElementById("countryselection");
var c_opt = document.createElement("option");
c_opt.text = "Please select";
c_opt.selected = true;
t.add(c_opt);
c_opt = document.createElement("option");
c_opt.text = "United Kingdom";
c_opt.value = "1";
t.add(c_opt);
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
var x = xmlDoc.getElementsByTagName("country");
for (i = 0; i < x.length; i++) {
var opt = document.createElement("option");
opt.text = x[i].getElementsByTagName("country_name ")[0].childNodes[0].nodeValue;
t.add(opt);
}
}
function county(Country) {
if (!document.getElementById("countyselection")) {
if (Country === "1") {
xmlRequest("counties.xml");
document.getElementById("quiz").innerHTML += "<select id='countyselection'></select>";
var t = document.getElementById("countyselection");
var y = xmlDoc.getElementsByTagName("county");
for (j = 0; j < y.length; j++)
{
var opt = document.createElement("option");
var txt = y[j].getElementsByTagName("county_name")[0].childNodes[0].nodeValue;
opt.text = txt;
t.add(opt);
}
}
} else {
var f = document.getElementById("countyselection");
document.getElementById("countyselection").parentNode.removeChild(f);
}
}
Because you're calling the function, not referencing it, and you have a space in the function name.
change
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
to
document.getElementById("countryselection").addEventListener("change", function() {
county(this.value);
}, false);
Also note that things like this
country_selector.id = "cou n tryselection";
is completely invalid, you can't use random text with spaces as an ID

Javascript - Loop through select options clicking each one

I am trying to go through a select list with 200+ entries and click on each one. When an element is clicked on it executes a function selectCountry() which adds a line to a table. I want to have it create a table with every option selected. The page of interest is at: http://www.world-statistics.org/result.php?code=ST.INT.ARVL?name=International%20tourism,%20number%20of%20arrivals.
So far I have the following, but it doesn't seem to work:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {selectCountry(opt.value)}
I am trying to do this in the console in Chrome.
One of the most useful features of dev tools is that when you write the name of a function, you get back its source code. Here's the source code for the selectCountry function:
function selectCountry(select) {
if (select.value == "000") return;
var option = select.options[select.selectedIndex];
var ul = select.parentNode.getElementsByTagName('ul')[0];
var choices = ul.getElementsByTagName('input');
for (var i = 0; i < choices.length; i++)
if (choices[i].value == option.value) {
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('[]');
return;
}
var li = document.createElement('li');
var input = document.createElement('input');
var text = document.createTextNode(option.firstChild.data);
input.type = 'hidden';
input.name = 'countries[]';
input.value = option.value;
li.appendChild(input);
li.appendChild(text);
li.onclick = delCountry;
ul.appendChild(li);
addCountry(option.firstChild.data, option.value);
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('');
}
Your flaw is now obvious. selectCountry accepts the entire select element as an argument as opposed to the select's value (which is a terrible design but meh). Instead of passing the value of the element, change its index:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var i = 0; i < opts.length; i++) {
sel.selectedIndex = i
selectCountry(sel)
}

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

Categories

Resources