I have a nested ASP.NET ListView, the outer one presenting groups of questions, and the inner one presenting distinct questions within the group. Some of the questions are presented as drop down lists. I want to detect the selected value on change without doing a postback. I have seen lots of references that look like “$(#control).val()” but I need a bit more flexibility.
I am adding the JavaScript in the C# code and it looks like this:
js = string.Format("javaScript:setInputSelectOption('{0}'); return false;", hidSelector.Value);
ddlInputSelectOptions.Attributes.Add("onchange", js);
The resultant aspx file contains this generated code;
<div id='Management_q2'>
<input type="hidden" name="ctl00$body$lstExecutive$ctrl1$hidSelector" id="ctl00_body_lstExecutive_ctrl1_hidSelector" value="Management" />
<select name="ctl00$body$lstExecutive$ctrl1$ddlInputSelectOptions"
id="ctl00_body_lstExecutive_ctrl1_ddlInputSelectOptions"
onchange="javaScript:setInputSelectOption('Management'); return false;">
<option value="0">Not Present</option>
<option selected="selected" value="1">Occasionally</option>
<option value="2">Customarily and Regularly</option>
<option value="3">Constantly</option>
</select>
</div>
My .js file contains this code:
function setInputSelectOption(question) {
var n = $('[id$=' + question + '_q2]>[id$=hidSelector]').val();
var v = $('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]');
setDDLData(n, v);
}
Using Chrome, I have tried these variants on the “var v = ” line with the corresponding results:
$(‘[id$=’ + question + ‘_q2]>[id$=ddlInputSelectOptions]’):
d.fn.d.init[1] $(‘[id$=’ + question +
‘_q2]>[id$=ddlInputSelectOptions]’).value: undefined $(‘[id$=’ +
question + ‘_q2]>[id$=ddlInputSelectOptions]’).val(): “”
So I am (yet again) looking for the right incantion to utter to jQuery so that it will return the selected value from the DDL.
I would suggest keeping it simple. Add a data- attribute to the DDL you wish to get the values from. Use jQuery to find the value.
Then in JS.
Also, if the JS is only for UI logic, it’s best to keep it out of the C# code and run it on the page ready using jQuery. So in your JS file.