I'm extremely new to JavaScript and am stumped on this one. I'm trying to send the ClientID of a Control to a js function. The function should then find the element and get the Control's value. To note: I am using a master page, and the Control I am passing the ClientID of is in a UserControl.
ASP:
//code here
<asp:TableCell runat="server">
<asp:DropDownList runat="server" ID="variableDDL"/>
//some ListItems
</asp:Tablecell>
//more cells here
<asp:TableCell runat="server">
<asp:ImageButton runat="server" ID="iButton" ImageUrl="~/Images/iButton.png" OnClientClick="iButtonClick(<%=variableDDL.ClientID%>);"/>
</asp:TableCell>
//code here
.js:
function iButtonClick(ClientID)
{
var v = document.getElementById(ClientID);
var val = v.value;
alert(val);
}
Every time I click the button, nothing happens. Changing the sent parameter to <%#variableDDL.ClientID%> does the same thing. Changing it to '<%=variableDDL.ClientID%>' or '<%#variableDDL.ClientID%>' gives a null pointer error since it can't find the object. The script is referenced correctly, and does fire if I change it to not accept a parameter and just produce an alert. Anyone know what I'm doing wrong?
EDIT: The requested code is shown below.
ASP UserControl:
protected void Page_Init(object sender, EventArgs e) {
DataTable fields = (DataTable) Session["fields"];
for(int i = 0; i < fields.Rows.Count; i++)
{
variableDDL.Items.Add(new ListItem(fields.Rows[i]["Field"].ToString(), fields.Rows[i]["Field"].ToString();
}
}
Rendered OnClick HTML:
'<%=variableDDL.ClientID%>' produces
onclick="iButtonClick('<%=variableDDL.ClientID%>');"
<%=variableDDL.ClientID%> produces
onclick="iButtonClick(<%=variableDDL.ClientID%>);"
'<%#variableDDL.ClientID%>' produces
onclick="iButtonClick('<%#variableDDL.ClientID%>');"
<%#variableDDL.ClientID%> produces
onclick="iButtonClick(<%#variableDDL.ClientID%>);"
By the look of it,
OnClientClick="iButtonClick(<%=variableDDL.ClientID%>);"
is getting rendered literally - it's not replacing the contents of the angle brackets.
Try
OnClientClick='iButtonClick("<%=variableDDL.ClientID%>");'
Note the single quotes for the property - I think this does make a difference - and the double quotes so the result becomes a JavaScript string literal.
If this doesn't work, you might have to set
iButton.OnClientClick = "iButtonClick('" + variableDDl.ClientID + "');";
in an event in your codebehind.
If you are not against jQuery, you could easily perform this operation by adding an identifying class to your select element, since it gets a unique client id.
<select id="variableDDL" class='varddl'>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button id="btn1" type="button">Click here</click>
$("#btn1").click(function(e){
var v = $(".varddl:first-child").val();
alert('Value of '+ $(".varddl:first-child").attr('id') + 'is ' + v);
});
Click here to view the fiddle
UPDATE: Pure JS Version
function btnClick(e){
//Select the first occurance, [0]
var ele = document.getElementsByClassName('varddl')[0];
if(ele){
//There's the value
var val = ele.value;
alert(val);
}
}
var btn1 = document.getElementById("btn1");
btn1.onclick = btnClick
;
Here is the JS Only Fiddle
This is how ASP.Net works: you cannot use servercode (<%%>) inside ASP.Net WebControls.
You can solve this by putting the ClientID directly in the javascript code:
function iButtonClick()
{
var v = document.getElementById('<%= variableDDL.ClientID %>');
var val = v.value;
alert(val);
}
You can also pass an object directly in the OnClientClick, with the restriction that you can only send the object itself:
OnClientClick="ButtonClick(this);"
Related
I have defined a variable in C# as the item selected in a drop down.
string parametername = ddlCarrier.SelectedItem.Text;
I now want to pass this variable in my URL to the next page. How do I do this in the href tag?
<asp:LinkButton href="Table.aspx?parameter=<%parametername%>" ID="btnSubmit" runat="server">Click Here</asp:LinkButton>
Purely Server-Side Approach
Instead of a LinkButton, you might want to consider using a HyperLink or <a> tag as you aren't going to be doing anything with your code-behind:
<asp:HyperLink ID="btnSubmit" runat="server" NavigateUrl="Table.aspx" Text="Navigate"></asp:HyperLink>
Then you can use the NavigateUrl property, which you might want to consider setting within your code-behind :
// This will set up your Navigation URL as expected
btnSubmit.NavigateUrl = String.Format("Table.aspx?parameter={0}",ddlCarrier.SelectedItem.Text);
If you use this approach, you may want to explicitly set that a PostBack occurs when your DropDownList changes so that this value will consistently be correct :
<asp:DropDownList ID="dllCarrier" runat="server" AutoPostBack="True" ...>
Client-Side Approach
However, if you are expecting to be able to change this to reflect the current value of your Carrier DropDownList without a PostBack, then you'll likely need to resort to Javascript to populate the value prior to actually navigating :
<!-- Set your base URL within the method and append the selected value when clicked -->
<asp:Button ID="Example" runat="server" OnClientClick="ClientSideNavigate('Table.aspx'); return false;" Text="Navigate"></asp:Button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
Or you could just avoid ASP.NET Controls altogether and just use an <button> tag :
<button onclick="ClientSideNavigate('Table.aspx'); return false;">Navigate</button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
You need to handle TextChanged or SelectedIndexChanged event for ddlCarrier and properly set href property of btnSubmit to include ddlCarrier.Text.
I'm trying to use the following Ajax AutoCompleteExtender:
<asp:TextBox runat="server" Width="300" ID="tbxItem" CssClass="NormalUpper" />
<asp:AutoCompleteExtender ID="autoCompleteExtenderItemName" runat="server"
MinimumPrefixLength="1" ServicePath="../Services/AutoCompleteSpecialOrders.asmx"
ServiceMethod="GetItems" CompletionInterval="100"
Enabled="True" TargetControlID="tbxItem" CompletionSetCount="15" UseContextKey="True"
EnableCaching="true" ShowOnlyCurrentWordInCompletionListItem="True"
CompletionListCssClass="dbaCompletionList"
CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListItemCssClass="AutoExtenderList" DelimiterCharacters="">
OnClientItemSelected="ItemSelected"
</asp:AutoCompleteExtender>
<asp:HiddenField runat="server" ID="hiddenItemId" />
We're using Master Pages (asp.net 4.0), User Controls and UpdatePanels. I'm having difficulty getting the OnClientItemSelected="ItemSelected" JavaScript/Jquery function to work. Here is the ScriptManagerProxy:
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" >
<Scripts>
<asp:ScriptReference Path="../common/script/AutoExtend.js"/>
</Scripts>
</asp:ScriptManagerProxy>
And here is the contents of AutoExtend.js (JavaScript & Jquery):
//function ItemSelected(sender, eventArgs) {
// var hdnValueId = "<%= hiddenItemId.ClientID %>";
// document.getElementById(hdnValueId).value = eventArgs.get_value();
// alert(hdnValueId.value);
// document.getElementById("tbxCatalogQty").focus();
// This try didn't work for me}
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
alert(hdnValueId.value);
document.getElementById("tbxCatalogQty").focus();
} //Neither did this one.
The alert DOES show the correct value from our WebService drop-down-type list! I just can't seem to set the hidden field to this value so I can use it in the code-behind later. It always shows as "" when run in the debugger. Also, the .focus() method doesn't set the focus to the tbxCatalogQty field like I would like. I've also tried this with single-quotes and that didn't change anything either.
In my code behind, I've tried accessing the hidden field as follows without any luck:
//var itemId = Request.Form[hiddenItemId.Value];
var itemId = hiddenItemId.Value;
I've seen a couple of similar posts out there: 12838552 & 21978130. I didn't see where they mentioned anything about using Master Pages and User Controls and inside of an UpdatePanel (not sure that makes any difference, however).
With the help of a friend, he just figured out the solution. First, we did a JavaScript postback, passing in the value like this:
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
window.__doPostBack('UpdatePanelOrdersDetails', hdnValueId.value);
}
Then, in the ASP:Panel that contained the AutoCompleteExtender, we added the "Onload="pnlInputCat_Load" parameter.
<asp:Panel ID="pnlInputCat" runat="server" OnLoad="pnlInputCat_Load">
Then, in the code behind, we added the pnlInputCat_Load method to look like this:
protected void pnlInputCat_Load(object sender, EventArgs e)
{
var theId = Request["__EVENTARGUMENT"];
if (theId != null && !theId.Equals(string.Empty))
{
Session["ItemCode"] = Request["__EVENTARGUMENT"];
tbxCatalogQty.Focus();
}
}
There certainly might be better ways to make this work, but I now have the ItemCode in a session variable for later access and I could then set focus on the Catalog Qty textbox.
Thanks for anyone who tried to understand/answer the above question.
I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/
I have a ASP.NET bulleted list control that, until today, was created and used only for plain text. A new design request asks that I turn SOME of those items into hyperlinks. Therefore the bulleted list will ultimately need to contain some plain text items, and some hyperlinks. If I change it to DisplayMode=Hyperlink, even if I leave the value blank, the entries that should just be plain text still become clickable links.
One solution that I think I can make work, is to use a Literal control and use HTML (<a href...) on the lines that need to be links. That will entail a little bit of re-working some old code, so before I try that I really want to know if this is possible to do with the existing BulletedList.
EDIT:
I seriously couldn't find anything about this anywhere, and I generally consider myself a pretty good Googler. So for the one or two lost and confused souls who find themselves in the same scenario sometime in the next decade, here is my complete implementation of the excellent answer offered below:
In the page's code-behind:
foreach (SupportLog x in ordered)
{
blschedule.Items.Add(new ListItem(x.Headline, "http://mysite/Support/editsupportlog.aspx?SupportLogID=" + x.SupportLogID));
}
blschedule.DataBind();
Note the DataBind at the end --- this is necessary to fall into the DataBound event:
protected void blschedule_DataBound(object sender, EventArgs e)
{
foreach (ListItem x in blschedule.Items)
{
if (x.Value.Contains("http")) //an item that should be a link is gonna have http in it, so check for that
{
x.Attributes.Add("data-url", x.Value);
}
}
}
In the .aspx page's head:
<script src="<%# ResolveClientUrl("~/jquery/jquery141.js") %>" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#<%=blschedule.ClientID %> li').each(function () {
var $this = $(this);
var attr = $this.attr('data-url');
if (typeof attr !== 'undefined' && attr !== false) {
$this.html('' + $this.text() + '');
}
});
});
</script>
The if statement is required to make sure to only turn the items that have the "data-url" attribute into links, and not turn ALL items into links.
You may find it's easier to use an <asp:Repeater /> for that task.
Something like:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li><%# string.IsNullOrEmpty(Eval("url").ToString()) ? Eval("text") : string.Format("{1}", Eval("url").ToString(), Eval("text").ToString()) %></li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
Hackalicious Way
set the URL value to DataValueField when data binding the BulletedList
use the DataBound event to iterate through the items and add an attribute to each one with a URL value
protected void BulletedList1_DataBound(object sender, EventArgs e)
{
foreach (ListItem i in BulletedList1.Items)
{
if (i.Value.Length > 0)
{
i.Attributes.Add("data-url", i.Value);
}
}
}
use JavaScript/jQuery to apply the necessary markup:
$('[data-url]').each(function() {
var $this = $(this);
$this.html('' + $this.text() + '');
});
didn't test this jQuery but it should be close
How to get dropdown list selected value in Label without autopostback and update panel in asp.net. i want the client side scripting for this code
i have the following code :-
protected void DropDownList1_TextChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
// DropDownList1.Attributes["onclick"] =
//"Label1.Text=this.options[this.selectedIndex].value";
}
If you don't want to use jquery (not everyone does! :) ) you can do it with standard javascript
<script language="javascript" type="text/javascript">
function setLabelText() {
var dropdown = document.getElementById("DropDownList1");
document.getElementById("Label1").innerHTML = dropdown.options[dropdown.selectedIndex].text;
}
</script>
<asp:DropDownList ID="DropDownList1" ClientIDMode="Static" runat="server" AutoPostBack="false" onchange="setLabelText();">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two" />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Label" ClientIDMode="Static"></asp:Label>
In your CS code, add an attribute such as:
ddlMyDrop.attributes.add("onchange","SetLabel(this,lblCtrl)");
In your JS code...
function SetLabel(sender, target){
$(target).val($(sender).val());
}
This assumes you reference jQuery.
You can do this fairly easily with jQuery. Label's turn into span and DropDownList into select on client side. Keep in mind that asp.net loves to append strings to the resultant content id's, e.g. MainContent_...
$(document).ready(function () {
$('#MainContent_DropDownList1').change(function () {
try {
$('#MainContent_Label1').text($(this + "option:selected").text());
} catch (err) {
alert(err);
}
});
});
Not using jQuery or Javascript as this is a fix of an existing site and it was not designed that way. Well I have gotten to a point where when the DropDownList is selected and does it's postBack I do my logic of setting the textBox readOnly status to true or false. the problem I have now is the the selectValue is not consistant. Wht it show in the selct field is not what is posted back to the page. Say I have None, 5.00, 10.00, 15.00, 20.00 as my choices to choose. I first choose 10.00 and it posts back None then I choose 20.00 it shows 10.00. It posts back the prior select value. the entire site is written from the code behind page. the aspx page is completely written from the .vb page. Everything is written into asp tags. here is the code;
If Page.IsPostBack Then
If product_option_is_required > 0 then
myTextBox.ReadOnly= true
Else
myTextBox.ReadOnly= false
End if
For Each child_control As Control In productOptions.Controls
If TypeOf child_control Is DropDownList Then
Dim child_ddl As DropDownList = child_control
tempName = products.getProductDependant("product_option_name",product_option_id)
tempSelectText = products.getProductSelectDependant("product_option_detail_name",child_ddl.SelectedValue)
priceDependant.Text ="here" & child_ddl.ID & " " & child_ddl.SelectedIndex & " " & child_ddl.SelectedValue & " --" & tempSelectText
If child_ddl.Text = "None" then
myTextBox.ReadOnly = true
myTextBox.Text = "If selected above enter name"
Else
myTextBox.ReadOnly = false
myTextBox.Text = ""
End if
End If
next
End if