Solved

Javascript to add options to a select tag

Posted on 2009-04-07
4
1,536 Views
Last Modified: 2012-05-06
I have a page with 2 drop down boxes on it. The second one is filled with options after a selection in the first one is made. That part is working. It will be changed to read items from a database instead of static test options, but that's not a problem. What I need to know is how do you set the value attribute of an option tag being added through javascript? If you look at the attached code, you can see the options are loaded from xml that is sent to the page. The xml elements I am loading (for this test) are named < employee > and have an id attribute. I want that id attribute set as the value of the option when loading the dropdown, so the employee name is the text you select and the employee ID is what is submitted with the form. I tried setting o.value before the mySelect.add line, but that was submitting undefined for the select. Not sure how to do this. Thanks for the help!
index.html contains:
 
<html>
<head>
  <script language="javascript">
    var xhttp;
 
    function onSelectionChange(){
      var mySelect = document.forms[0].portfolio;
      if (mySelect.selectedIndex>-1){
        //instantiate XmlHttpRequest
 
          // Checking if IE-specific document.all collection exists 
          // to see if we are running in IE 
          if (document.all) { 
            xhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
           } else { 
          // Mozilla - based browser 
            xhttp = new XMLHttpRequest(); 
          }
          //hook the event handler
          xhttp.onreadystatechange = HandlerOnReadyStateChange;
          //prepare the call, http method=GET, true=asynchronous call
          xhttp.open("GET", 
            "http://localhost/category_test/getcats.aspx?portfolio=" + 
            mySelect.selectedIndex, true);
          //finally send the call
          xhttp.send();          
        }
      }
      function HandlerOnReadyStateChange(){
        var mySelect = document.forms[0].analyst;
        
        // This handler is called 4 times for each 
        // state change of xmlhttp
        // States are: 0 uninitialized
        //      1 loading
        //      2 loaded
        //      3 interactive
        //      4 complete
        if (xhttp.readyState==4){
          mySelect.innerHTML = "";
          
          //responseXML contains an XMLDOM object
          var nodes = xhttp.responseXML.selectNodes("//employee");
          for (var i=0; i<nodes.length; i++){
            var o = new Option();
              o.text = nodes(i).text;
            mySelect.add(o);
          }
        }
      }
    </script>
  </head>
  <body>
    <form id="form1" name="form1" action="showresults.aspx">
      <table>
        <tr>
          <td>Portfolio size:</td>
          <td>
            <select id="portfolio" name="portfolio" 
             onchange="onSelectionChange();">
              <option></option>
              <option>0 .. 10,000</option>
              <option>10,000 to 100,000</option>
              <option>Over 100,000</option>
            </select>
          </td>
        </tr>
        <tr>
          <td>Authorized financial analyst:</td>
          <td>
            <select id="analyst" name="analyst"> 
            </select>
          </td>
        </tr>
        <tr>
          <td>Comments</td>
          <td>
            <textarea name="comments" rows="3" cols="20"
              ID=Textarea1></textarea>
          </td>
        </tr>
      </table>
      <input type=submit>
    </form>
  </body>
</html>
 
getcats.aspx contains only:
 
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="getcats.aspx.vb" Inherits="HTUSearch.getcats" %>
 
getcats.aspx.vb contains:
 
Imports System.IO
Imports System.Xml
 
Partial Public Class getcats
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim xmlWriter As XmlTextWriter
 
        Response.Clear()
        Response.ContentEncoding = Encoding.UTF8
        Response.ContentType = "text/xml"
 
        Using tw As TextWriter = New StreamWriter(Response.OutputStream, Encoding.UTF8)
            xmlWriter = New XmlTextWriter(tw)
            xmlWriter.WriteStartDocument()
            xmlWriter.WriteStartElement("employees", "employees", "")
            xmlWriter.WriteStartElement("employee", "employee", "")
            xmlWriter.WriteAttributeString("id", "", "1")
            xmlWriter.WriteValue("Test 1")
            xmlWriter.WriteEndElement()
            xmlWriter.WriteStartElement("employee", "employee", "")
            xmlWriter.WriteAttributeString("id", "", "2")
            xmlWriter.WriteValue("Test 2")
            xmlWriter.WriteEndElement()
            xmlWriter.WriteEndElement()
            xmlWriter.WriteEndDocument()
        End Using
 
        xmlWriter.Close()
 
    End Sub
 
End Class

Open in new window

0
Comment
Question by:that_it_guy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 2

Accepted Solution

by:
AlvinLim84 earned 500 total points
ID: 24087949
Hi. This is the index.html code that I have made some changes on it. Hope this will help you
<html>
<head>
  <script language="javascript">
    var xhttp;
 
    function onSelectionChange(){
      var mySelect = document.forms[0].portfolio;
      if (mySelect.selectedIndex>-1){
        //instantiate XmlHttpRequest
 
          // Checking if IE-specific document.all collection exists 
          // to see if we are running in IE 
          if (document.all) { 
            xhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
           } else { 
          // Mozilla - based browser 
            xhttp = new XMLHttpRequest(); 
          }
          //hook the event handler
          xhttp.onreadystatechange = HandlerOnReadyStateChange;
          //prepare the call, http method=GET, true=asynchronous call
          xhttp.open("GET", 
            "http://localhost/category_test/getcats.aspx?portfolio=" + 
            mySelect.selectedIndex, true);
          //finally send the call
          xhttp.send();          
        }
      }
      function HandlerOnReadyStateChange(){
        var mySelect = document.forms[0].analyst;
        
        // This handler is called 4 times for each 
        // state change of xmlhttp
        // States are: 0 uninitialized
        //      1 loading
        //      2 loaded
        //      3 interactive
        //      4 complete
        if (xhttp.readyState==4){
          mySelect.innerHTML = "";
          
          //responseXML contains an XMLDOM object
          var nodes = xhttp.responseXML.selectNodes("//employee");
          for (var i=0; i<nodes.length; i++){
            var o = new Option(nodes(i).text, nodes(i).text); // new Option(text, value)              
            mySelect.add(o);
          }
        }
      }
    </script>
  </head>
  <body>
    <form id="form1" name="form1" action="showresults.aspx">
      <table>
        <tr>
          <td>Portfolio size:</td>
          <td>
            <select id="portfolio" name="portfolio" 
             onchange="onSelectionChange();">
              <option></option>
              <option>0 .. 10,000</option>
              <option>10,000 to 100,000</option>
              <option>Over 100,000</option>
            </select>
          </td>
        </tr>
        <tr>
          <td>Authorized financial analyst:</td>
          <td>
            <select id="analyst" name="analyst"> 
            </select>
          </td>
        </tr>
        <tr>
          <td>Comments</td>
          <td>
            <textarea name="comments" rows="3" cols="20"
              ID=Textarea1></textarea>
          </td>
        </tr>
      </table>
      <input type=submit>
    </form>
  </body>
</html>

Open in new window

0
 

Author Comment

by:that_it_guy
ID: 24087998
Getting closer! :)  The only problem is this sets the value of the option tag to the node text (nodes(i).text), so the same thing is still being submitted with the form as before. How would I set the value portion to the id attribute of the node? Thanks!
0
 

Author Comment

by:that_it_guy
ID: 24088229
Nevermind, I figured it out. I changed the line to:

var o = new Option(nodes(i).text, nodes(i).attributes.item(0).value); // new Option(text, value)

Thankyou for pointing me in the right direction on adding the value to the option!
0
 

Author Closing Comment

by:that_it_guy
ID: 31567537
Very helpful
0

Featured Post

Why You Need a DevOps Toolchain

IT needs to deliver services with more agility and velocity. IT must roll out application features and innovations faster to keep up with customer demands, which is where a DevOps toolchain steps in. View the infographic to see why you need a DevOps toolchain.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
.CSS HTML Help 3 58
How does GeoJson relates to Leaflet and Mapbox? 4 49
display data from multiple ajax calls 9 41
CSS styling problem 3 27
Does your audience prefer people in photos or no people? How can you best highlight what you’re selling? What are your competitors doing, and what can you do that is different and unique from them?  Continue reading to learn how to make your images …
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question