accessing object elements from javascript

Discussion in 'JavaScript' started by DmitryS, Mar 2, 2011.

  1. #1
    <script>
    function addString() {
    var text = document.myform.selectOption.value;
    var testNode = document.getElementById('test');
    var newNode = document.createElement('b');
    newNode.setAttribute("id",text);
    newNode.innerHTML = text;
    testNode.appendChild(newNode);
    }
    </script>

    <form name="myform" method="post" action="action">
    <select name="selectOption">
    <option value="option1">option1</option>
    <option value="option2">option2</option>
    <option value="option3">option3</option>
    </select>

    <input name="Add1" type="button" class="formtext" value="Add" onclick="addString();">

    <p id="test"></p>
    </form>

    I'm using javascript to grab the value picked from a dropdown menu and populate it below, which it works fine with the code above.
    The problem is that if I make the following change to the select name my javascript doesn't work anymore:

    Code:

    <script>
    ...
    var text = document.myform.selectOption[0].option.value;
    ...
    </script>

    <form>
    <select name="selectOption[0].option">
    ...
    </form>

    I get an error saying that document.myform.selectOption.0 is null or not an object

    How can I achieve the above using this sort of names, the name has to be this form, I cannot change it because they are an array of objects.

    Thanks in advanced.
     
    DmitryS, Mar 2, 2011 IP
  2. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm confused: :confused: Do all the elements have the name "selectOption[0].option"? In that case, use this:
    var text = document.getElementsByName("selectOption[0].option")[x].value;

    Of course, you change x to whatever element you want eg. 0 for the first, 1 for the second...

    But if the elements have unique names, this works:
    var text = document.getElementsByName("selectOption[x].option")[0].value;

    getElementsByName returns an array even if there is only one element with that name, so you need to have [0] on the end.

    But I would switch to IDs and get the value like this:
    var text = document.getElementById("selectOption[x].option").value;
     
    Last edited: Mar 2, 2011
    Cash Nebula, Mar 2, 2011 IP