Reputation:
Sorry for the basic silly question. But I really dont have any idea on how to solve this. I have ASP controls (One TextBox
and One DropDownList
). Now I need to access value
property of TextBox
as well as SelectedIndex
property of DropDownList
. This should be as simple as:
For TextBox
:
document.getElementById("<%= myControl.ClientID >").value
For DropDownList
:
document.getElementById("<%= myControl.ClientID %>").selectedindex
But in Visual Studio 2008, while I am writing these codes, it does not work. I can not find any value
or selectedindex
attribute for the respective control. I am not getting this, because in most forums and tutorials, they suggested in a simple way I mentioned.
HTML Code:
<div> <asp:TextBox ID="myText" runat="server" /> <asp:DropDownList ID="myList" runat="server" /> </div>
Is there any other way or I am just missing something here?
Upvotes: 0
Views: 5543
Reputation: 75073
first of all, jQuery helps you a lot writting javascript, you shoudl use this path.
To answer your question, you need to use MyControlId.ClientID
and not only MyControlId
for example:
var t = document.getElementById('<%= myTextBoxID.ClientID %>').value;
alert(t); // textbox value
var d = document.getElementById('<%= myDropDownID.ClientID %>'),
dSelected = d.options[d.selectedIndex].value;
alert(dSelected); // dropdown value
with jQuery this would simply be:
var t = $('#<%= myTextBoxID.ClientID %>').val(), // for your textbox
d = $('#<%= myDropDownID.ClientID %>').val(); // for your selectbox
alert(t ' --> ' + d);
Seams, from the comments that you still have no luck, then the problem must be in the control or the name itself, try this to debug the problem:
let's imagine that you have:
<asp:TextBox runat="server" id="MyTextBox" Text="Hello" />
write right below that line this:
<h2><%= MyTextBox.ClientID %></h2>
and open the inspector of your browser (Firebug or IE Dev tools) and run the javascript to see if you get the Hello
string, like this:
Note: I used MyTextBox
, please change it to the name that you got inside that <h2>
tag
Upvotes: 1
Reputation: 69372
Try using a single punctuation mark.
document.getElementById('<%= myTextBox.ClientID %>').value
A couple of answers recommend jQuery
but I think you should only use it if you need it. If you're only getting values from elements, then there shouldn't be a need to introduce a new library to your website. If you plan to use quite a bit of Javascript, animations, etc.. then jQuery would make sense.
Upvotes: 0
Reputation: 2472
Personally I'd use jQuery instead of standard JavaScript and then have a look at this question for how to find your element with it.
edit: if you haven't used jQuery before then make sure you wrap your code in its ready block otherwise it might not find your element:
$(document).ready(function() {
// work with your element ID here
});
Upvotes: 0