I'm trying to write a function that will take a selected item from a drop down list and add it to an array, which is then printed in a text field on the page, but I'm having trouble referencing the value.
Here's my function:
Code:
function addTool() {
if (document.forms[0].toolList.value == "")
window.alert("You must choose at least one item to purchase.");
else {
var dd1 = document.getElementById('toolList');
var toolArray = new Array();
var count = 0;
toolArray.push(dd1.options[dd1.selectedIndex].text);
document.forms[0].buyList.options[count].value = toolArray[count];
count++;
}
}
And the code which tries to use it:
Code:
<select name="toolList">
<option value="" style="display:none;"></option>
<option value="cDrill">Cordless Drill</option>
<option value="cScrew">Cordless Screwdriver</option>
<option value="circSaw">Circular Saw</option>
<option value="bandsaw">Bandsaw </option>
<option value="discsander">Disc Sander</option>
</select></p>
<p><select name = "buyList" multiple = "multiple"
size = "10" style = "width: 500px">
<option value = "none">Items to be purchased</option>
</select></p>
<p><input type = "button" value = "Add Tool"
onclick = "addTool();" style = "width: 120px" />
Right now I have no idea if I'm even close to having this correct. What would be the best way to do this?
Is there a way to make the selected items appear in a selectable list of options, like I have in my original code? I'd like to add a "remove item" button, and for that I need to be able to select the items that appear on the new list.
<body>
<form>
<select id="toolList">
<option value="" style="display:none;"></option>
<option value="cDrill">Cordless Drill</option>
<option value="cScrew">Cordless Screwdriver</option>
<option value="circSaw">Circular Saw</option>
<option value="bandsaw">Bandsaw </option>
<option value="discsander">Disc Sander</option>
</select></p>
<p><select name = "buyList" multiple = "multiple" size = "10" style = "width: 500px">
<option value = "none">Items to be purchased</option>
</select></p>
<p><input type = "button" value = "Add Tool" onclick = "addTool();" style = "width: 120px" />
</form>
</body>
<script>
var toolArray = [];
var count = 0;
function addTool() {
if (document.getElementById('toolList').value == "")
window.alert("You must choose at least one item to purchase.");
else {
var dd1 = document.getElementById('toolList');
toolArray.push(dd1.options[dd1.selectedIndex].text);
document.forms[0].buyList.options[count]=new Option(toolArray[count], toolArray[count++]);
}
}
</script>
I like this code because it's simpler than the other version posted here, but it doesn't work for me. It doesn't print the selected item into the box where it's supposed to.