javascript does not recognize my html elements - javascript

What I get is a blank page, although I should have a combo box. The array gets filled just fine - I alerted some values and it works, but the combo box does not show anything.
What I want to do is create a combobox from the data retrieved from the array, but it doesn't seem to work.
<script type="text/javascript">
var array = {"ADDRESS_ID":["3","5"],"ADDRESS_PLACE":["a","b"],"ADDRESS_PARENT":[null,null],"TYPE":["0","1"]};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function () {
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = array.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>
<div id="container_for_select_container">
</div>
</body>
</html>

Your code works fine apart from a few things. As mentioned the length of your Array is wrong. You need to have the array['ADDRESS_ID'].length instead of array.length and you need to either place the div with id 'container_for_select_container' before you JavaScript code or place your JavaScript code in a window.load function. Otherwise you are trying to append your select box to a HTML element that does not yet exist.
<div id="container_for_select_container"></div>
<script type="text/javascript">
var array = {
"ADDRESS_ID": ["3", "5"],
"ADDRESS_PLACE": ["a", "b"],
"ADDRESS_PARENT": [null, null],
"TYPE": ["0", "1"]
};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function() {
alert('You selected option ' + this.selectedIndex);
};
// Add some <option>s
numOptions = array['ADDRESS_ID'].length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>

The problem seems to be with your numOptions. Shouldn't it be:
numOptions = array['ADDRESS_ID'].length;
instead of
numOptions = array.length;?
Here's the working fiddle

You need to change your numOptions variable to:
numOptions = array['ADDRESS_ID'].length;
Working example in JSFiddle:
http://jsfiddle.net/reBSB/
New Code:
var array = {"ADDRESS_ID":["3","5"],"ADDRESS_PLACE":["a","b"],"ADDRESS_PARENT":[null,null],"TYPE":["0","1"]};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function () {
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = array['ADDRESS_ID'].length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);

Related

Adding onClick function to select elements

I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
var name = array[i];
var selectElement = document.getElementById(selectElementId);
addToSelectNode(document.getElementById(selectElementId), name);
var thisNode = selectElement.childNodes[i];
if (thisNode.value != "none")
{
thisNode.addEventListener("click", function(event)
{
appendNodeToList("artist-list", i);
selectElement.selectedIndex = 0;
selectElement.remove(selectElement.i);
selectElement.style.display = "none";
});
}
}
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
function appendNodeToList(listId, text)
{
var newNode = document.createElement("LI");
var textNode = document.createTextNode(text);
newNode.appendChild(textNode);
document.getElementById(listId).appendChild(newNode);
}
Didn't work at all though
A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
<option value="none">none</option>
</select>
JavaScript:
window.onload = function()
{
var dropdown = document.getElementById("sampleDropdown");
var n = array.length;
// Loop to add to <select> dropdown
for (var i = 1; i <= n; i++)
{
addToSelectNode(dropdown, array[i - 1]);
}
// Loop to add id's to each element in the dropdown
for (var i = 0; i <= n; i++)
{
dropdown[i].id = "selectNum" + i;
}
// Loop to add event listener
for (var i = 0; i < dropdown.length; i++)
{
dropdown[i].addEventListener("click", function(event)
{
// Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
dropdown.selectedIndex = 0;
if (event.target.id != "selectNum0")
{
// Disable once clicked
event.target.disabled = true;
// Do other things here in relation to event.target
}
});
}
}
var array =
[
"sampleText1", "sampleText2"
];
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}

Cannot read property 'undefined' of undefined? why this error is coming?

var select = document.getElementById("source");
var select2= document.getElementById("status");
var option = ["1", "2", "3", "4", "5","6","7","8","9"];
var option2= [];
function moveright() {
var a = source.options[source.selectedIndex].value;
var option = document.createElement("option");
option.text = a;
select2.add(option);
select.remove(i);
}
function moveleft() {
var b = status.option2[status.selectedIndex].value;
var option2 = document.createElement("option");
option2.text = b;
select.add(option2);
select2.remove(i);
}
for(i = 0; i < option.length; i++) {
var opt = option[i];
var a = document.createElement("option");
a.innerHTML = opt;
a.value = opt;
select.appendChild(a);
}
for(i = 0; i < option2.length; i++) {
var opt2 = option2[i];
var a = document.createElement("option");
a.innerHTML = opt2;
a.value = opt2;
select2.appendChild(a);
}
<select id = "source" multiple size = "10" onclick = "moveright ()">
<option>Choose a number</option>
</select>
<select id = "status" multiple size = "10" onclick = "moveleft ()">
<option>Choose a number </option>
</select>
I am new to JavaScript I am trying to push the drop down values from one drop down to another. First drop down is working, but second drop down is not working. Can anyone help me? I tried only in the JavaScript array.
Slightly changed, but giving you expected results ;)
Working fiddle
In your moveright and moveright you had a variable i which was not defined. I assume you wanted to use selected option index to remove itself.
And you should write full selector for getting elements, not using it's id directly. Browser picked up source id and returned as html element, however it could not do that with status, because there is such property as window.status.

Passing One's Self to OnClick Event JavaScript

The on click event that I add to an input in javascript isn't working in the proper manner.
My code so far looks like so:
function order(option) {
if(option.checked) {
document.getElementId("col_order").value = document.getElementById("col_order").value + " " + option.value;
}
}
...//somewhere further down
for(var i = 0; i < options.length; i++) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.onclick = "order(check)"; //Problem here
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
}
I have also tried:
check.onclick = (function() { var option = check; return function() {order(option);}})();
The problem that I am having is the check.onlick line of code. When I add this with normal HTML:
<input type = "checkbox" name = "order_list[]" onclick = "order(this)" value = "randVal">randVal</input>
I don't have any problem whatsoever; the method executes with the intended results. Any thoughts?
Let me clarify: I make it to the order function just fine, but I never get into the if statement, even though the checkbox was just clicked
Use addEventListener instead, and even if it looks like it should work, you're overwriting the same variables on each iteration as there is no closure in for loops, so I would probably add a closure to avoid issues.
For a checkbox you would listen for the change event, not click
for(var j = 0; j < options.length; j++) {
(function(i) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.addEventListener('change', function() {
if (this.checked) {
var col_order = document.getElementById("col_order");
col_order.value = col_order.value + " " + this.value;
}
}, false);
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
})(j);
}
FIDDLE
check.onclick = "order(check)"; assigns a String as an on-click handler. That doesn't work; the browser expects a function there:
check.onclick = function() {
order(check);
}

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