Link to home
Start Free TrialLog in
Avatar of flynny
flynnyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

help getting the selected value of dropdownlist clientside using javascript

hi,

i have a dropdownlist that is inside a modal window (using smartmodal jquery plugin).

when the dropdownlist is shown i want to save the selected value to a hiddenfield clientside so i can pick it up serverside. Now the reason i don't add autopostback=true is because if i add this and the dropdown is changed it postsback to the server and the modal is hidden again.

now i have tried the following;

<asp:DropDownList ID="eDropDown" OnChange="javascript:setExercise();" AutoPostBack="false" runat="server" />

with

function setExercise() {
    var dropdownIndex = document.getElementById('eDropDown').selectedIndex;
    var dropdownValue = document.getElementById('DropDown')[dropdownIndex].value;
    alert(dropdownValue);
}

however it always returns the first instance of the dropdownlist.

the dropdown data is bound in the pageload event inside a if not page.postback check.

any ideas?

matt
Avatar of zzynx
zzynx
Flag of Belgium image

You posted this question in the Java topic area while it is a javaScript question.
Since java <> javascript you'll get more answers if you post a link to this question over there.
typo, the id for the second "document.getElementById()" call is different.
function setExercise() {
    var dropdownIndex = document.getElementById('eDropDown').selectedIndex;
    var dropdownValue = document.getElementById('eDropDown')[dropdownIndex].value;
    alert(dropdownValue);
}

Open in new window

Avatar of flynny

ASKER

sorry (i did correct this), but the problem still remains and the selected value doesnt seem to be changing.
So, what is the output of the alert()?  Anything useful?

Can you expand the function to provide more information?

What browser are you using?
function setExercise() {
  var sel = document.getElementById('eDropDown')
  if ( sel ) {
    var index = sel.selectedIndex
    var value = sel.value || sel.options[ index ].innerHTML
    alert( 'Index: ' + index + '\nValue: ' +  value )
  } else {
    alert( 'Element not found.  id="eDropDown"' )
  }
}

Open in new window

Avatar of flynny

ASKER

Hi thanks for the quick reply,

using your method it is always returning index:0 value:1 (which is the first element). I've also tried adding it to a second dropdownlist.

could the fact that both are inside a modal box have anything to do with it? (long shot)

i've tried it in safari, mozilla and ie and all are returning the same.

any ideas?
Please show the associated HTML...

Avatar of flynny

ASKER

ok heres the html and javascript i'm currently using
********************************HTML*******************************************************
        <div id="rel_modal_exercise" class="hidden">
	        <h1>Add a New Exercise</h1>
	            <p>Please select new exercise to add to workout:<asp:DropDownList ID="eDropDown" OnChange="javascript:setExercise();" AutoPostBack="false" runat="server" /></p>
	            <asp:HiddenField ID="selectedExercise" runat="server" />
	            <p>Select the number of sets/intervals :<asp:DropDownList ID="setsDropDown"  OnChange="javascript:setSetNumber();" AutoPostBack="false" runat="server" /></p>
	            <asp:HiddenField ID="selectedSets" runat="server" />
	            <p><asp:Button ID="addExercise" text="Add Exercise" OnCommand="AddExerciseClick" runat="server" /></p>
        </div>
********************************JAVASCRIPT*************************************************
$(document).ready(function() {
    //$('#addSectionModal').modal();
    //$('#addExerciseModal').modal();
$('.ExerciseModal').modal();
});
 
 
function setExercise() {
    var sel = document.getElementById('exerciseDropDown')
    if (sel) {
        var index = sel.selectedIndex
        var value = sel.value || sel.options[index].innerHTML
        alert('Index: ' + index + '\nValue: ' + value)
    } else {
        alert('Element not found.  id="exerciseDropDown"')
    }
}
 
function setSetNumber() {
    var sel = document.getElementById('setsDropDown')
    if (sel) {
        var index = sel.selectedIndex
        var value = sel.value || sel.options[index].innerHTML
        alert('Index: ' + index + '\nValue: ' + value)
    } else {
        alert('Element not found.  id="setsDropDown"')
    }
}
********************************BINDING IN ASPX.VB*****************************************
          oQRY = "SELECT exerciseID, longname FROM exercise ORDER BY longName"
            exerciseDropDown.DataSource = CreateDataSource(oQRY)
            exerciseDropDown.DataValueField = "exerciseID"
            exerciseDropDown.DataTextField = "longName"
            exerciseDropDown.DataBind()
 
            'populate the setsDropdown
            setsDropDown.Items.Add("1")
            setsDropDown.Items(0).Value = 1
            setsDropDown.Items.Add("2")
            setsDropDown.Items(1).Value = 2
            setsDropDown.Items.Add("3")
            setsDropDown.Items(2).Value = 3
            setsDropDown.Items.Add("4")
            setsDropDown.Items(3).Value = 4
            setsDropDown.Items.Add("5")
            setsDropDown.Items(4).Value = 5
            setsDropDown.Items.Add("6")
            setsDropDown.Items(5).Value = 6
            setsDropDown.Items.Add("7")
            setsDropDown.Items(6).Value = 7
            setsDropDown.Items.Add("8")
            setsDropDown.Items(7).Value = 8
            setsDropDown.Items.Add("9")
            setsDropDown.Items(8).Value = 9
            setsDropDown.Items.Add("10")
            setsDropDown.Items(9).Value = 10

Open in new window

ooh...  I was thinking that the document element being referenced was a SELECT
statment...

But it's not, it's an "asp:DropDownList"...

That's why selectedIndex is 0, there is no selectedIndex for a DropDownList.

I wonder what kind of HTML element is created by "asp:DropDownList"?
function setSetNumber() {
  var sel = document.getElementById('setsDropDown')
  if (sel) {
    var index = sel.selectedIndex
    var value = sel.value || sel.options[index].innerHTML
    alert('Index: ' + index + '\nValue: ' + value + '\nNodeName: ' + sel.nodeName )
  } else {
    alert('Element not found.  id="setsDropDown"')
  }
}

Open in new window

It looks like you are going to need to use something like

SelectedItem.Text

not

selectedIndex


function setSetNumber() {
  var sel = document.getElementById('setsDropDown')
  if (sel) {
    var value = sel.SelectedItem.Text
    alert('Value: ' + value + '\nNodeName: ' + sel.nodeName )
  } else {
    alert('Element not found.  id="setsDropDown"')
  }
}

Open in new window

Avatar of flynny

ASKER

thanks for the reply.

ok, (with the last code you added) it doesn't seem to like the

var value = sel.SelectedItem.Text

line?

That was a guess.  Let's find out what the document element contains...

Get the objDisplay.js from this question

https://www.experts-exchange.com/questions/23817882/Traversing-the-DOM-in-IE6.html

Add this to the HTML so that we can access the contain function(s)

<script type='text/javascript' src='objDisplay.js'></script>

Add this "div" at the end of your HTML:

<div id='debug'></div>

and let's change setSetNumber() to be something like:

Then, try it, and copy the contents of the debug output here please.
function setSetNumber() {
  var sel = document.getElementById('setsDropDown')
  if (sel) {
    var debug = document.getElementById('debug')
    if ( debug ) {
      debug.innerHTML =  objDisplay( 'setsDropDown', sel )
    }
  } else {
    alert('Element not found.  id="setsDropDown"')
  }
}

Open in new window

Avatar of flynny

ASKER

ok here it is. ans once again thanks for all your help.

setsDropDown: { parentNode : [object HTMLParagraphElement], tabIndex : 0, blur(), focus(), nodeName : "SELECT", nodeValue : null, nodeType : 1, childNodes : [object NodeList], firstChild : [object Text], lastChild : [object Text], previousSibling : [object Text], nextSibling : null, attributes : [object NamedNodeMap], ownerDocument : [object HTMLDocument], insertBefore(), replaceChild(), removeChild(), appendChild(), hasChildNodes(), cloneNode(), normalize(), isSupported(), namespaceURI : null, prefix : null, localName : "SELECT", hasAttributes(), ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12, tagName : "SELECT", getAttribute(), setAttribute(), removeAttribute(), getAttributeNode(), setAttributeNode(), removeAttributeNode(), getElementsByTagName(), getAttributeNS(), setAttributeNS(), removeAttributeNS(), getAttributeNodeNS(), setAttributeNodeNS(), getElementsByTagNameNS(), hasAttribute(), hasAttributeNS(), id : "setsDropDown", title : "", lang : "", dir : "", className : "", type : "select-one", selectedIndex : 0, value : "1", length : 10, form : [object HTMLFormElement], options : [object HTMLOptionsCollection], disabled : false, multiple : false, name : "setsDropDown", size : 0, add(), remove(), item(), namedItem(), boxObject : [object BoxObject], offsetTop : 0, offsetLeft : 0, offsetWidth : 0, offsetHeight : 0, offsetParent : null, innerHTML : " 1 2 3 4 5 6 7 8 9 10 ", scrollTop : 0, scrollLeft : 0, scrollHeight : 0, scrollWidth : 0, clientTop : 0, clientLeft : 0, clientHeight : 0, clientWidth : 0, contentEditable : "inherit", spellcheck : false, style : [object CSSStyleDeclaration], removeEventListener(), dispatchEvent(), baseURI : "http://localhost:50023/admin/workout/create_workout.aspx", compareDocumentPosition(), textContent : " 1 2 3 4 5 6 7 8 9 10 ", isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), getUserData(), DOCUMENT_POSITION_DISCONNECTED : 1, DOCUMENT_POSITION_PRECEDING : 2, DOCUMENT_POSITION_FOLLOWING : 4, DOCUMENT_POSITION_CONTAINS : 8, DOCUMENT_POSITION_CONTAINED_BY : 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 32, getElementsByClassName(), getClientRects(), getBoundingClientRect() }
Whoa, it IS a SELECT...
And selectedIndex IS 0...

Can you take a screen shot for me?
Avatar of flynny

ASKER

ok heres one if you need any more let me know.

matt.
screenshot1.jpg
Wow, that image would seem to imply that the id attribute being used within the setSetNumber() function is not the one associated with the Select list being changed.

 <p>Select the number of sets/intervals :<asp:DropDownList ID="setsDropDown"  OnChange="javascript:setSetNumber();" AutoPostBack="false" runat="server" /></p>

So, I wonder with what the following ASP code is associated...

<asp:DropDownList ID="setsDropDown"  ...

Interesting.

What do we get if, instead of passing "nothing" to the setSetNumber() function, we pass an object reference instead.

OnChange="javascript:setSetNumber(this);"

and changing the setSetNumber() function to tell us what is actually passed in?
function setSetNumber( obj ) {
  var sel = document.getElementById('setsDropDown')
 
  var debug = document.getElementById('debug')
  if ( debug ) {
    debug.innerHTML =  objDisplay( 'setsDropDown()', obj )
  }
 
  if (sel) {
    alert( sel.nodeName )
  } else {
    alert('Element not found.  id="setsDropDown"')
  }
}

Open in new window

Avatar of flynny

ASKER

hi sorry about the delay

setsDropDown(): { onchange(), parentNode : [object HTMLParagraphElement], nodeName : "SELECT", nodeValue : null, nodeType : 1, childNodes : [object NodeList], firstChild : [object Text], lastChild : [object Text], previousSibling : [object Text], nextSibling : null, attributes : [object NamedNodeMap], ownerDocument : [object HTMLDocument], insertBefore(), replaceChild(), removeChild(), appendChild(), hasChildNodes(), cloneNode(), normalize(), isSupported(), namespaceURI : null, prefix : null, localName : "SELECT", hasAttributes(), tagName : "SELECT", getAttribute(), setAttribute(), removeAttribute(), getAttributeNode(), setAttributeNode(), removeAttributeNode(), getElementsByTagName(), getAttributeNS(), setAttributeNS(), removeAttributeNS(), getAttributeNodeNS(), setAttributeNodeNS(), getElementsByTagNameNS(), hasAttribute(), hasAttributeNS(), id : "setsDropDown", title : "", lang : "", dir : "", className : "", type : "select-one", selectedIndex : 5, value : "6", length : 10, form : [object HTMLFormElement], options : [object HTMLOptionsCollection], disabled : false, multiple : false, name : "setsDropDown", size : 0, tabIndex : 0, add(), remove(), blur(), focus(), ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12, item(), namedItem(), boxObject : [object BoxObject], offsetTop : 86, offsetLeft : 223, offsetWidth : 41, offsetHeight : 20, offsetParent : [object HTMLDivElement], innerHTML : " 1 2 3 4 5 6 7 8 9 10 ", scrollTop : 0, scrollLeft : 0, scrollHeight : 160, scrollWidth : 39, clientTop : 1, clientLeft : 2, clientHeight : 160, clientWidth : 39, contentEditable : "inherit", spellcheck : false, style : [object CSSStyleDeclaration], removeEventListener(), dispatchEvent(), baseURI : "http://localhost:50023/admin/workout/create_workout.aspx", compareDocumentPosition(), textContent : " 1 2 3 4 5 6 7 8 9 10 ", isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), getUserData(), DOCUMENT_POSITION_DISCONNECTED : 1, DOCUMENT_POSITION_PRECEDING : 2, DOCUMENT_POSITION_FOLLOWING : 4, DOCUMENT_POSITION_CONTAINS : 8, DOCUMENT_POSITION_CONTAINED_BY : 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 32, getElementsByClassName(), getClientRects(), getBoundingClientRect() }

also interestingly the message box read SELECT
Notice how here, the value of selectedIndex is now 5...

Interestingly enough, both here, and earlier, the id attribute is "setsDropDown" (as expected).

So, what alert dialog box is displayed if you change the routine to be something like:
function setSetNumber( obj ) {
  var sel = document.getElementById('setsDropDown')
 
  var debug = document.getElementById('debug')
  if ( debug ) {
    debug.innerHTML =  objDisplay( 'setsDropDown()', obj )
  }
 
  if ( sel && sel.nodeName == 'SELECT' ) {
    var index = sel.selectedIndex
    var value = sel.value || sel.options[ index ].innerHTML
    alert( 'Index: ' + index + '\nValue: ' +  value )
  } else {
    alert('Element not found.  id="setsDropDown"')
  }
}

Open in new window

Avatar of flynny

ASKER

setsDropDown(): { onchange(), parentNode : [object HTMLParagraphElement], nodeName : "SELECT", nodeValue : null, nodeType : 1, childNodes : [object NodeList], firstChild : [object Text], lastChild : [object Text], previousSibling : [object Text], nextSibling : null, attributes : [object NamedNodeMap], ownerDocument : [object HTMLDocument], insertBefore(), replaceChild(), removeChild(), appendChild(), hasChildNodes(), cloneNode(), normalize(), isSupported(), namespaceURI : null, prefix : null, localName : "SELECT", hasAttributes(), tagName : "SELECT", getAttribute(), setAttribute(), removeAttribute(), getAttributeNode(), setAttributeNode(), removeAttributeNode(), getElementsByTagName(), getAttributeNS(), setAttributeNS(), removeAttributeNS(), getAttributeNodeNS(), setAttributeNodeNS(), getElementsByTagNameNS(), hasAttribute(), hasAttributeNS(), id : "setsDropDown", title : "", lang : "", dir : "", className : "", type : "select-one", selectedIndex : 6, value : "7", length : 10, form : [object HTMLFormElement], options : [object HTMLOptionsCollection], disabled : false, multiple : false, name : "setsDropDown", size : 0, tabIndex : 0, add(), remove(), blur(), focus(), ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12, item(), namedItem(), boxObject : [object BoxObject], offsetTop : 86, offsetLeft : 223, offsetWidth : 41, offsetHeight : 20, offsetParent : [object HTMLDivElement], innerHTML : " 1 2 3 4 5 6 7 8 9 10 ", scrollTop : 0, scrollLeft : 0, scrollHeight : 160, scrollWidth : 39, clientTop : 1, clientLeft : 2, clientHeight : 160, clientWidth : 39, contentEditable : "inherit", spellcheck : false, style : [object CSSStyleDeclaration], removeEventListener(), dispatchEvent(), baseURI : "http://localhost:50023/admin/workout/create_workout.aspx", compareDocumentPosition(), textContent : " 1 2 3 4 5 6 7 8 9 10 ", isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), getUserData(), DOCUMENT_POSITION_DISCONNECTED : 1, DOCUMENT_POSITION_PRECEDING : 2, DOCUMENT_POSITION_FOLLOWING : 4, DOCUMENT_POSITION_CONTAINS : 8, DOCUMENT_POSITION_CONTAINED_BY : 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 32, getElementsByClassName(), getClientRects(), getBoundingClientRect() }

no again i get index 0 value 1 as the alert.
ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This could occur if there are two document elements that are of type SELECT
that have the same ID attribute!
Avatar of flynny

ASKER

yes that cracked it!!

but there isn't any dropdowns in the page with the same id???
Avatar of flynny

ASKER

hmm thank you so much for your help though its been much appreciated. you really were a god send.
They don't have to be the same type.  Any to items on the same page with the same id mean that the 2nd, or subsequent, can't be located using the document.getElementById().  The id attribute is supposed to be unique...
Avatar of flynny

ASKER

From looking at the html code when runnign the smart modal jquery code appears to create a new overlay div. inserting the code inside the relevent hidden div. This is why there will be two copies of the same dropdown.


again thank you for your help.

matt
You are welcome.  Is there anything else, or are you going to accept an answer as the solution?
Avatar of flynny

ASKER

Brilliant, quick replies that helped to pinpoint the answer, easy and clear to understand and friendly.
Thanks for the grade, the points, and the kind words.

Good luck & have a great day