PDA

View Full Version : Adding Options to a Select element



fileserverdirect
12-12-2007, 09:20 PM
Hello,
I googled this topic and got some code, but It does not seam to be working:

document.getElementById("SelectList").options[i] = new Option('new text','new value');
with SelectList being the select element.
When I load the page "ERROR: Line xxx: Object Expected."
I am calling it inside a function, I don't know if that means anything but...
Also I read that it will overwrite anything that is already there, Is there a way to make it so that It justs adds to the list? Thanks,

jscheuer1
12-13-2007, 07:21 AM
As far as I know:


new Option

would have to refer to a function named Option. Go back to where you found this code and find the function.

Using the DOM, you can add an option element to a select element:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function Option(t,v){
var ot=document.createTextNode(t);
var o=document.createElement('option')
o.value=v;
o.appendChild(ot);
return o;
}
</script>
</head>
<body>
<form action="#">
<div>
<input type="button" value="add"
onclick="document.getElementById('test').appendChild(new Option('new text','new value'));">
<br>
<select id="test" name="something">
<option value="existing value">existing text</option>
</select><br>
<input type="submit" value="Go!">
</div>
</form>
</body>
</html>

fileserverdirect
12-13-2007, 01:30 PM
Thanks,
I tried your example and it works! But as soon as I change it to fit my page, It says that document.getElementById("SelectList"); is null or not an object. YES there is a select list on this page with an ID like this. I use another script on this select box and it has no problem with getElementById("SelectList");.
Maybe it's the changes that I made? I am not using a button to call it, I call it inside a function, and it's supposed to each time the function is run, add a new option to the select element.

While I was writing this post, I think I figured out whats going on, but not how to stop it. I think that when It is called inside a function, it goes nuts because it is not being called on the document as was your example was. How can I solve this problem?

jscheuer1
12-13-2007, 04:26 PM
Don't be thinking like that. Just because something is inside a function doesn't mean it cannot find an element. However, if the function is executed before the element is parsed, there will be problems.

Also, I wouldn't rule out typos or other "stupid" mistakes, or just something I'm not thinking of because I cannot see the full code. If you need more help:

Please post a link to the page on your site that contains the problematic code so we can check it out.

fileserverdirect
12-13-2007, 07:06 PM
Thanks, I ended up creating two functions, one function to print the varables, and one to add it to the select list (If you have no idea what I am talking about, you would have had to have seen the document, PS: I am running the script locally so I cannot post a link ;)). Anyways Everything Works, I mean ALMOST Everything works, and the one thing that does not work is a BIG ONE. Another script on my page, Pick list(http://www.javascriptkit.com/script/script2/picklist.shtml) Scans the HTML for options, but when ANY thing is added: "Runtime error on line XX: Object doesn't support this property or method" when the user clicks "->" to move one option to another select field. On that line:while (selectIndex > -1). *slaps head* Is there any way to fix this?

jscheuer1
12-13-2007, 07:26 PM
I'm not having that problem:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function addOpt(f, e, t, v){
var el=f.form.elements[e], Option=function(t,v){
var ot=document.createTextNode(t), o=document.createElement('option')
o.value=v; o.appendChild(ot); return o;
}
el.appendChild(new Option(t,v));
}

// PickList script- By Sean Geraty (http://www.freewebs.com/sean_geraty/)
// Visit JavaScript Kit (http://www.javascriptkit.com) for this JavaScript and 100s more
// Please keep this notice intact

// Control flags for list selection and sort sequence
// Sequence is on option value (first 2 chars - can be stripped off in form processing)
// It is assumed that the select list is in sort sequence initially
var singleSelect = true; // Allows an item to be selected once only
var sortSelect = true; // Only effective if above flag set to true
var sortPick = true; // Will order the picklist in sort sequence

// Initialise - invoked on load
function initIt() {
var selectList = document.getElementById("SelectList");
var selectOptions = selectList.options;
var selectIndex = selectList.selectedIndex;
var pickList = document.getElementById("PickList");
var pickOptions = pickList.options;
pickOptions[0] = null; // Remove initial entry from picklist (was only used to set default width)
if (!(selectIndex > -1)) {
selectOptions[0].selected = true; // Set first selected on load
selectOptions[0].defaultSelected = true; // In case of reset/reload
}
selectList.focus(); // Set focus on the selectlist
}

// Adds a selected item into the picklist
function addIt() {
var selectList = document.getElementById("SelectList");
var selectIndex = selectList.selectedIndex;
var selectOptions = selectList.options;
var pickList = document.getElementById("PickList");
var pickOptions = pickList.options;
var pickOLength = pickOptions.length;
// An item must be selected
while (selectIndex > -1) {
pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
pickOptions[pickOLength].value = selectList[selectIndex].value;
// If single selection, remove the item from the select list
if (singleSelect) {
selectOptions[selectIndex] = null;
}
if (sortPick) {
var tempText;
var tempValue;
// Sort the pick list
while (pickOLength > 0 && pickOptions[pickOLength].value < pickOptions[pickOLength-1].value) {
tempText = pickOptions[pickOLength-1].text;
tempValue = pickOptions[pickOLength-1].value;
pickOptions[pickOLength-1].text = pickOptions[pickOLength].text;
pickOptions[pickOLength-1].value = pickOptions[pickOLength].value;
pickOptions[pickOLength].text = tempText;
pickOptions[pickOLength].value = tempValue;
pickOLength = pickOLength - 1;
}
}
selectIndex = selectList.selectedIndex;
pickOLength = pickOptions.length;
}
selectOptions[0].selected = true;
}

// Deletes an item from the picklist
function delIt() {
var selectList = document.getElementById("SelectList");
var selectOptions = selectList.options;
var selectOLength = selectOptions.length;
var pickList = document.getElementById("PickList");
var pickIndex = pickList.selectedIndex;
var pickOptions = pickList.options;
while (pickIndex > -1) {
// If single selection, replace the item in the select list
if (singleSelect) {
selectOptions[selectOLength] = new Option(pickList[pickIndex].text);
selectOptions[selectOLength].value = pickList[pickIndex].value;
}
pickOptions[pickIndex] = null;
if (singleSelect && sortSelect) {
var tempText;
var tempValue;
// Re-sort the select list
while (selectOLength > 0 && selectOptions[selectOLength].value < selectOptions[selectOLength-1].value) {
tempText = selectOptions[selectOLength-1].text;
tempValue = selectOptions[selectOLength-1].value;
selectOptions[selectOLength-1].text = selectOptions[selectOLength].text;
selectOptions[selectOLength-1].value = selectOptions[selectOLength].value;
selectOptions[selectOLength].text = tempText;
selectOptions[selectOLength].value = tempValue;
selectOLength = selectOLength - 1;
}
}
pickIndex = pickList.selectedIndex;
selectOLength = selectOptions.length;
}
}

// Selection - invoked on submit
function selIt(btn) {
var pickList = document.getElementById("PickList");
var pickOptions = pickList.options;
var pickOLength = pickOptions.length;
if (pickOLength < 1) {
alert("No Selections in the Picklist\nPlease Select using the [->] button");
return false;
}
for (var i = 0; i < pickOLength; i++) {
pickOptions[i].selected = true;
}
return true;
}

</script>
</head>
<body onload="initIt();">
<form NAME="theform" ID="theform" ACTION="whatever" onSubmit="return selIt();">
<table>
<tr>
<td>
<input type="button" value="add" onclick="addOpt(this,'SelectList','new text','new value');">
<br><select NAME="SelectList" ID="SelectList" SIZE="5" multiple="multiple" style="width: 150px">
<option VALUE="01sel">Selection 01</option>
<option VALUE="02sel">Selection 02</option>

<option VALUE="03sel">Selection 03</option>
<option VALUE="04sel">Selection 04</option>
<option VALUE="05sel">Selection 05</option>
<option VALUE="06sel">Selection 06</option>
<option VALUE="07sel">Selection 07</option>
<option VALUE="08sel">Selection 08</option>
<option VALUE="09sel">Selection 09</option>
<option VALUE="10sel">Selection 10</option>
</select>

</td>
<td>
<input type="button" value="->" onclick="addIt();">
<br>
<input type="button" value="<-" onclick="delIt();">
</td>
<td>
<select NAME="PickList" ID="PickList" SIZE="5" multiple="multiple" style="width: 150px">
<option VALUE="01sel">Selection 01</option>
</select>
</td>
</tr>
<tr>
<td ALIGN="left">
<input TYPE="reset" VALUE="Reset" ONCLICK="javascript: window.location.href = 'picklist.html'">
</td>

<td>
</td>
<td ALIGN="right">
<input TYPE="submit" VALUE="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>

fileserverdirect
12-13-2007, 07:54 PM
Did you try to remove all the options?
ERROR: Runtime error on line 73
--------------------------------------------------
IT DOESN'T WORK ANY MORE!!!:(:(:confused::confused::(
Even when I removed the code that added the exta value. Huh, I will Attach the full source, and remove it after you've looked at it, for saftey reasons.
WHAT IS GOING ON?!?
(note that images/songs are not included in this file)
P.S. you have to change the extension from .txt to .htm

jscheuer1
12-13-2007, 09:32 PM
Removing all options causes an error even without my code. But the error I got was for this line:


selectOptions[0].selected = true

which appears in two places, and it was the second one where the problem was. The first one is near where you got the error, so might as well add this in both places (additions red):


if (selectOptions[0] && !(selectIndex > -1)) {
selectOptions[0].selected = true; // Set first selected on load
selectOptions[0].defaultSelected = true; // In case of reset/reload
}

Then later:


if(selectOptions[0])
selectOptions[0].selected = true;
}

// Deletes an . . .

fileserverdirect
12-13-2007, 10:12 PM
You Missunderstood, I was tring to tell you that when I implicated my script to yours, it did not work. It did not solve MY problem. There is no way I am re-implimenting the Picklist script, I have added so much stuff to it. Did you try to run the file? It says that there is somthing wrong with this while loop that wasn't before:

while (selectIndex > -1) {
pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
pickOptions[pickOLength].value = selectList[selectIndex].value;
// If single selection, remove the item from the select list
if (singleSelect) {
selectOptions[selectIndex] = null;
}
if (sortPick) {
var tempText;
var tempValue;
// Sort the pick list
while (pickOLength > 0 && pickOptions[pickOLength].value < pickOptions[pickOLength-1].value) {
tempText = pickOptions[pickOLength-1].text;
tempValue = pickOptions[pickOLength-1].value;
pickOptions[pickOLength-1].text = pickOptions[pickOLength].text;
pickOptions[pickOLength-1].value = pickOptions[pickOLength].value;
pickOptions[pickOLength].text = tempText;
pickOptions[pickOLength].value = tempValue;
pickOLength = pickOLength - 1;
}
}
IDK:confused:?

jscheuer1
12-13-2007, 10:43 PM
I will look at your file when I have more time. Did you try adding the test(s) I suggested? They are pretty straightforward, and you would had to have radically altered the original javascriptkit script for them to no longer apply. They simply test to see if the element is available before taking action, a good practice in any script.

fileserverdirect
12-14-2007, 08:40 PM
Yes, I did try your "fixes" but they were not related to what the problem was, I acutally have items in the select list. Anyways I have modified the script a little, no luck...:rolleyes: Any on your end?

jscheuer1
12-14-2007, 10:48 PM
Sorry, it's easy to get distracted around here. Anyways, I downloaded Kiosk.txt and it doesn't appear to have any option to add to the select list. :confused:

fileserverdirect
12-14-2007, 11:59 PM
Try un-commenting line 472 first:

// p('test','testing')
Sorry, I was playing around with it when I uploaded it :)
AND
That's what I have been saying, It is being called in a function, not throgh a button.
The whole point of this script was to easily add songs to the Kiosk, It's for a client(family member, same diff), and they are not exactly "Codders" so I told them to add two easy functions c(); and p(); in certain areas. Thats it,
Thanks,

jscheuer1
12-15-2007, 09:16 AM
I'm getting no error in FF with or without that line uncommented. I am getting an error in IE with or without that line uncommented. I think I see the problem, and this (or something similar) happened to me while I was writing my code (line 64):


pickOptions[pickOLength] = new Option(selectList[selectIndex].text);

should be:


pickList.appendChild(new Option(selectList[selectIndex].text));

Similarly line 104:


selectOptions[selectOLength] = new Option(pickList[pickIndex].text);

should be:


selectList.appendChild(new Option(pickList[pickIndex].text));

I don't think I ever told you to do it the way you were there in those two spots, but maybe I did. I think though, that code was from somewhere else, not me. There could also still be other problems.

Now, if I just fixed something other than what you were talking about, well, um IDK - it's hard to hit a moving target.

fileserverdirect
12-15-2007, 04:15 PM
Well, you hit the target!
It works!
Just one more thing:
Is it possable to use the function e(); to do what p(); was doing so that you dont have to write them both? Maybe a new function that adds the p(); function AFTER the select box, all in one function, (sorry it's hard to say without saying "function":))
This is just to make adding new songs easier.
:D

jscheuer1
12-15-2007, 05:02 PM
I'm not clear on what you hope to accomplish by combining e() and p(). Do you mean allow p() to be called from a button or something added to the markup that is generated by e()?

One thing I can tell you is that after the page loads, you cannot use e(). It will overwrite the entire page.

fileserverdirect
12-15-2007, 06:59 PM
O.K. I guess I wasn't that clear:rolleyes:
--
What I mean is, in e(), it adds the select items to the list after it prints the "Listen" section. You said that this would result in an error because "SelectList" did not exist yet, thats why I made p() after the select list. This is a little bit of a hassel to write two functions, when a function is supposed to be a short cut to cut down on programming. But, I was hoping that there was a way to one use one function to do both jobs.
---
Totally random "not-shure-if-it-will-even-work" idea:
What if function e(song, mp3) {...} was after the select list, so it could carry on in adding the options to the list BUT it added the markup code to the table by searching for the table's id\name?
---
Thanks,

jscheuer1
12-16-2007, 12:45 AM
I'm perhaps going to have to come back to this when I have more time to help sort out the details with you.

But e() writes directly to the page, while p() adds elements to the page, a major difference. If e() were changed so as to add elements, rather than to write their code, both p() an e() could be run together, but this would have to be after any element that they were adding to was already parsed.