Getting ASP dropdownlist selected value using javascript - javascript

I have a dropdownlist in asp as below:
<asp:DropDownList ID="ddlActiveStatus" AutoPostBack="True" runat="server" onchange = "dconfirm()" OnSelectedIndexChanged = "ddlActiveStatus_SelectedIndexChanged">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="Y">Y</asp:ListItem>
<asp:ListItem Value="N">N</asp:ListItem>
</asp:DropDownList>
I would like to retrieve the value of selected index when user selects on a different set of values. I have a code like this:
function dconfirm(){
var e = document.getElementById("<%=ddlActiveStatus.ClientID%>");
var selVal = e.options[e.selectedIndex].value;
alert(selVal);}
Expected result is when user selects 'Y', the javascript will alert 'Y'. However the program kept throwing below error:
The name 'ddlActiveStatus' does not exist in the current context
I would like to get it done using javascript only. What have I missed out? Kindly advise.
Thank you.

While technically what you're doing should work, you can avoid referencing ddlActiveStatus.ClientID in your JavaScript by adding ClientIDMode="Static" directly on the ddlActiveStatus control.
Doing this gives you full control over the ID generated for the control so you can then simply use the following in your JavaScript:
var e = document.getElementById("ddlActiveStatus");

ASP sometimes changes the ID. Add a "Name" to the element like so:
<asp:DropDownList Name="DdlActiveStatus" ID="ddlActiveStatus" AutoPostBack="True" runat="server" onchange = "dconfirm()" OnSelectedIndexChanged ="ddlActiveStatus_SelectedIndexChanged">
Then use: var x = document.getElementsByName("DdlActiveStatus");
Or, you could use jquery:
$('[name="DdlActiveStatus"]').doStuff();

$('#ddlActiveStatusoption').val()
or
$('select#ddlActiveStatusoption:selected').val())

I've figured out a workaround for this. Hopefully it'll be able to help someone who're looking for answer.
Instead of getting the selected values of ddlActiveStatus in my javascript, I'll be passing the value by adding below code to my dropdownlist property as below:
onchange = "dconfirm(this.value)"
As for my javascript function it'll display the user selected value. Code as below:
function dconfirm(values)
{
alert(values);
if (values == 'Y')
{
//do something
}
}
This does the job for me. Hope it helps.
Thanks guys for your helpful replies, cheers.

the easy way for me is
var VarName = $('#<%=YouDropDownId.ClientId %>').val();
for your case you forget #
try this i hope it works
var e = document.getElementById('#<%=ddlActiveStatus.ClientID %>');
good luck.

Related

How to clear rad listbox items from client side

I have a radlistbox i want clear the radlistbox items. i had tried this code but not working as expected.Can someone give me a idea how can i do this.
Thanks.
<telerik:RadListBox RenderMode="Lightweight" runat="server" AllowReorder="True" AllowDelete="true" ID="RadListBox1" Height="200px" Width="230px" AutoPostBack="false" ButtonSettings-AreaWidth="35px">
<ButtonSettings Position="Right" AreaWidth="35px"></ButtonSettings>
</telerik:RadListBox>
Script:
function ClearListbox()
{
var listBox = $find('<%=RadListBox1.ClientID%>');
listBox.trackChanges();
listBox.clearSelection();
listBox.commitChanges();
}
The clearSelection method just removes the highlight from the selected item.
You should use the get_items().remove or removeAt methods to succeed:
var lb = $find("ctl00_ContentPlaceholder1_RadListBoxSource");
var item = lb.get_selectedItem();
lb.trackChanges();
lb.get_items().remove(item);
lb.commitChanges();
You will also need a selection to be able to remove the selected item.
Check out this article for more information https://docs.telerik.com/devtools/aspnet-ajax/controls/listbox/radlistbox-items/working-at-client-side#removing-items
If you're seeing this now and wondering how to clear 'ALL' items in the RadListBox using javascript. There's a clear method that's weirdly hard to find info on. Code below:
var lb = $find("<%= yourListNameHere.ClientID %>");
lb.trackChanges();
lb.get_items().clear();
lb.commitChanges();

How to access asp hiddenfield value from UserControl in Javascript (getElementByID not working)

So I've gotten stuck trying to access a HiddenField value in my UserControl from my JavaScript.
In my user control I have:
<asp:HiddenField ID="HiddenField1" runat="server" />
This user control is used in multiple places and sometimes multiple times on the same page so ClientIDMode = Static is not an option, and it must be runat = server as I need to access it in the code behind as well.
In my JavaScript I have tried the following:
document.getElementById('<%= HiddenField1.ClientID %>');
document.getElementById('HiddenField1');
$find("<%= HiddenField1.ClientID %>");
All of these return null. I have seen a number of "solutions" suggest
document.getElementById('ctl00_ContentPlaceHolder1_HiddenField1')
But that obviously poses problems for re-usability.
EDIT:
The html generated by this is:
<input type="hidden" name="ctl00$ctl00$MainContent$MainContent$$ctl00$SomeUserControl$someOtherUserControl1$HiddenField1" id="MainContent_MainContent_SomeRepeater_SomeUserControl_0_someOtherUserControl1_0_HiddenField1_0" value="353">
The value is set in the code behind through other functions.
EDIT2: Generalised my code example
I couldn't find a way to make this work with hidden field and so I caved and just changed my object to an asp:Label with a CSSClass and stored the value in the text property.
Not the best solution I know, but if anybody has a better suggestion please let me know.
In code behind may be your code look like this
public void test()
{
hdnvalue.Value = "Test";
//After assign the value you should call client side function
ClientScript.RegisterStartupScript(GetType(), "Script", "<script
language='javascript'>gethidden()</script>", false);
}
In javascript function should use like this
<script language="javascript" type="text/javascript">
function gethidden() {
var hdn = document.getElementById('<%=hdnvalue.ClientID%>');
alert(hdn.value);
}
</script>
I hope its help to you.

How can I get the text from an Asp.Net TextBox control with Jquery or Javascript?

I have an Asp.Net TextBox control:
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom"></asp:TextBox>
In a separate Jquery/Javascript file, I would like get the text from it... normally the text is like '9/1/2015'.
I have tried the following:
var r2FromDate = new Date($(".txtFromDate").val);
var r2FromDate = new Date($(".txtFromDate").val.toString());
var r2FromDate = new Date($(".txtFromDate").val());
var r2FromDate = new Date($(".txtFromDate").text());
var r2FromDate = new Date($(".txtFromDate").text);
and the same with using the # <%= txtFromDate.ClientID %> notation and it completely breaks with that.
Please help!
$('#txtFromDate').val();
You want to select using the ID, not the class.
var text = $("#<%=txtFromDate.ClientId %>").val();
ASP should then output the ID generated on the client and your javascript can select it. You can also reuse this variable instead of querying the DOM over and over [it has to find it every time you use jQuery like "$(...)"].
If your javascript is located in another file, you can use the name attribute instead
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom" name="txtFromDate"></asp:TextBox>
$('input[name="txtFromDate"]').val();
https://api.jquery.com/attribute-equals-selector/
Alternatively, you can define the following property on your TextBox
ClientIDMode="static"
That will ensure that your ID on the client side will be the same as the server side id.
And then you can use:
$('#txtFromDate').val();
It was actually because I put the id as 'txtFromDate' and the class as 'txtDateFrom' instead of keeping them the same. I was trying to access the class 'txtFromDate' when it didn't exist.
.val() works when you select the right class.
You can try this through this you can also get asp button or any control for that matter.
var txt_txtFromDate = document.querySelector("input[id*='txtFromDate']");
alert(txt_txtFromDate.Value);
you can also try querySelectorAll() if you have multiple controls with same id in client side.
Also, $("input[id*='txtFromDate']") will work.

how to get value in javascript for asp Label control?

Suppose I have asp Lable set in markup like:
<asp:Label ID="myID" runat="server"></asp:Label>
then set value for this Label in code behind like:
myID.Text =100
then I want get the value 100 in javascript. I tried:
document.getElementById('<%=myID.ClientID%>').value;
but is not working. How to resolve this issue?
I believe that labels render as spans. Try getting the inner text.
document.getElementById('<%=myID.ClientID%>').innerText;
With jquery you need to use the html property.
var g = $('#<%=myID.ClientID%>').html();
These will NOT work with jquery
$('#<%=myID.ClientID%>').innerText
$('#<%=myID.ClientID%>').innerHTML
$('#<%=myID.ClientID%>').val()
var label=$("#<%myID.ClientID%>").html();

Passing ClientId of a textbox to use it in a javascript function

this is my control:
<asp:TextBox ID="txt_rol" onkeyup="this.value=this.value.toUpperCase()" runat="server" BorderColor="#E0E0E0" BorderStyle="Solid" Width="240px"></asp:TextBox>
</strong>
<asp:ImageButton ID="imgBtnGuardar" runat="server" ImageUrl="~/imagenes/boton.guardar.jpg" OnClientClick="ValidaCajadeTextoVacia(document.getElementById('<%=txt_rol.ClientId%>'));MensajeCargandoJQUERY();"/>
The problem is, that i can't get the Id of the textbox.
Well, right off the bat I can tell you that there's a syntax issue in the code. It should be:
'<%= txt_rol.ClientID %>'
There may be other obstacles you need to overcome here too. For example, if these controls are nested in a GridView you won't be able to reference the control that way.
function masterClick(clicked, controlID) {
var dynCtrl = clicked.id.substring(0, clicked.id.lastIndexOf("_") + 1);
var tBox = document.getElementById(dynCtrl + controlID);
tBox.value = "";
tBox.focus();
}
Then call from your image button like...
masterClick(this,'txt_rol');
change tBox.value and focus to whatever action you like, but should have access to the control in JavaScript now. You can add in a check like " if (tBox) " to ensure you have an object. The downside is the static reference to the control within the inline javascript, and you have to adjust when the calling control is in a different container, grid, panel, etc.
Check the output with View Source and you will understand what is happening. You'll have to set the OnClientClick property server-side (onload). Or find a way to bind it OnClientClick='<%#SomeProperty%>'.
Another option could be to use jQuery to find your control:
$("input:text[id*=txt_rol]")
By the way: your JavaScript won't work if someone pastes in the textbox using the mouse (right-click/paste).

Categories

Resources